var x = 3;
(function (){
console.log('before', x);
var x = 7;
console.log('after', x);
return ;
})();
In the above code var X is initialized globally. So inside the function the first console.log should print "before 3" but i don't get it. The reason is that i am trying to re-declare the global variable.
Can somebody explain why this is happening?
var x = 3;
(function (){
console.log('before', x);
var x = 7;
console.log('after', x);
return ;
})();
In the above code var X is initialized globally. So inside the function the first console.log should print "before 3" but i don't get it. The reason is that i am trying to re-declare the global variable.
Can somebody explain why this is happening?
Share Improve this question edited Nov 18, 2012 at 2:06 Joseph Quinsey 9,97210 gold badges57 silver badges80 bronze badges asked Nov 2, 2012 at 10:13 harikrishharikrish 2,0293 gold badges21 silver badges40 bronze badges 1- 1 Link answering your question: adequatelygood./2010/2/JavaScript-Scoping-and-Hoisting FWIW, you're looking at "hoisting". – Florian Margaine Commented Nov 2, 2012 at 10:16
3 Answers
Reset to default 5In the above code var X is initialized globally. so inside the function the first console.log should print "before 3".
No, it should print before undefined
, because var
takes effect from the beginning of the function regardless of where you write it.
Your code is exactly the same as this:
var x = 3;
(function (){
var x;
console.log('before', x);
x = 7;
console.log('after', x);
return ;
})();
And of course, variables start with the value undefined
.
Details: Poor misunderstood var
The JavaScript parser does Variable Hoisting when parsing your code. This means that any variable declaration will be moved to the top of the current scope, thus in your case, this code will get executed:
var x = 3;
(function (){
var x;
console.log('before', x);
x = 7;
console.log('after', x);
return ;
})();
So your local variable x
gets declared at first with an initial value of undefined
.
This should explain, why you get an "beforeundefined" for the first console.log()
.
The scope of a variable is much simpler than in other languages. It doesn't start at declaration but is either :
- the function in which you have the declaration
- the global scope if the declaration isn't in a function
MDN :
The scope of a variable declared with var is the enclosing function or, for variables declared outside a function, the global scope (which is bound to the global object).
You can imagine that all variable declarations are moved to the start of the scope (the function). So this is exactly like
var x = 3;
(function (){
var x;
console.log('before', x); // now undefined
x = 7;
console.log('after', x); // now 7
return ;
})();
Be careful to understand what is the exact scope (the function, not the block) :
var x = 3;
(function (){
console.log('before', x); // this is undefined !
if (true) {
var x = 7;
}
return ;
})();