Mike Lewis Mike Lewis - 6 months ago 14
Javascript Question

JavaScript var keyword: redefining a variable's value inside a closure

What am I missing here? This behaves as expected:

var x = 1;
(function(){
// x === 1
})();


But,

var x = 1;
(function(){
var x = x;
// x is undefined
})();


I would think that x should be
1
. It seems as though the
var x = x
nukes the value of x before it is assigned. Is this a bug? This doesn't seem very intuitive.

Was this behavior changed? I remember doing something like this in the past.

For reference:

var x = 1;
(function(){
var y = x;
// y === 1
})();


And:

var x = 1;
(function(){
x = x;
// x === 1
})();

Answer
var x = 1;
(function(){
   var x = x;
})();

After variable hoisting becomes:

var x = 1;
(function(){
   var x;
   x = x;
})();