Real Red.
Real Red.

Reputation: 5039

Weird behavior in referring to global variable. Is this a bug in javascript? Surely it isn't!

Consider the following piece of code.

<html>
<body>
<script>  
var x = 5; //globally declared
function showX() 
{ 
      alert("x="+x); //trying to display global value

      var x=10; //trying to create and initialize a local x
}
</script>
<input type = "button" value="Show X" onclick="showX()"> 
</body>
</html>

The alert statement shows 'x=undefined'. And doesn't print the global value of x as expected. An equivalent java code would display 5! So, is it a bug? If not then how does one explain that behavior?

Upvotes: 2

Views: 321

Answers (3)

Magnar
Magnar

Reputation: 28830

The second var-declaration is interfering with the first. You are actually referring to the as-of-yet-undeclared local x. However, to quote javascript guru Douglas Crockford:

JavaScript's biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.

http://www.jslint.com/lint.html

So the recommendation is to avoid using global variables as much as possible.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502076

The scope of x is the block function in which it is declared... although I believe scope in JavaScript can be a bit tricky sometimes. In C# this would be a compile-time error - it would be trying to use the local variable before its declaration.

Whatever the reason, I'd try to avoid doing it simply for the sake of readability.

Upvotes: 1

Greg
Greg

Reputation: 321766

The ECMAScript Specification says in section 12.2:

If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in s10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in 10.1.3) using property attributes { DontDelete}. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

So it's not a bug - the local variable is created when the function is entered.

Upvotes: 5

Related Questions