0

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);
8
  • 1
    A design error. This flaw has been removed in ES5 strict mode. Commented Jul 12, 2011 at 13:34
  • Why not? I suppose it could make naming conflicts, but you should be giving better variable names if that is an issue. Commented Jul 12, 2011 at 13:35
  • 1
    Source for my statement above: es5.github.com/#C (fourth bullet) Commented Jul 12, 2011 at 13:40
  • 1
    And a live demo that demonstrates this: jsfiddle.net/simevidas/r3Hjp/1 (doesn't work in older browsers) Commented Jul 12, 2011 at 13:43
  • Thank you Šime, could you post these comments as an answer? Commented Jul 12, 2011 at 13:45

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.