titus
titus

Reputation: 5784

javascript variable scoping

Why does javascript allow the creation of global variables in local code?
An example

function f() { x=10; }
function g() { print(x); }
f(x);
g(x);

Upvotes: 0

Views: 80

Answers (3)

jenovachild
jenovachild

Reputation: 1781

I think you need to specify var before the variable declaration to make it in scope.

Upvotes: 0

Quentin
Quentin

Reputation: 943142

Why does javascript allow the creation of global variables in local code?

Because it isn't a perfect language.

Use the var keyword to limit the scope of variables.

Upvotes: 1

Radu
Radu

Reputation: 8699

When you don't preface variables with var they are automatically in the global scope.

Upvotes: 3

Related Questions