Xinrui Ma Xinrui Ma - 9 months ago 27
HTML Question

JavaScript Hoisting declaration confusion when using Immediately-invoked function expression

Get confused.

var message = "Xinrui Ma";

var call = (function(){
message = "I am cool";
})();

alert(message);


From my perspective, the code will be treated like this:

var message = "Xinrui Ma";

var call = (function(){
var message; // it will add message declaration here
message = "I am cool";
})();

alert(message); // this should alert the "Xinrui Ma", not the "I am cool",
// cause Hoisting is JavaScript's default behavior of moving all declarations
// to the top of the current scope


But in fact, it outputs "I am cool", why is that????

Answer Source

If you don't have a variable declaration inside a function, it uses the variable from the containing scope. It doesn't create a new local variable -- there wouldn't be any way to refer to closure variables if it did that.

This has nothing to do with hoisting, which only occurs when you declare the variable in the function. Hoisting would apply if you wrote:

var call = (function() {
    message = "I am cool";
    var message;
})();

In this case, the var declaration would be hoisted to the top of the function.