In this mozilla article, I read:
Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense “hoisted” or lifted to the top of the function or statement. However, variables that aren’t initialized yet will return a value of undefined.
And then some examples:
/**
* Example 1
*/
console.log(x === undefined); // logs "true"
var x = 3;
/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
Example 2, above, will be interpreted the same as:
var myvar = "my value";
(function() {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();
I fail to see anything being “hoisted”—at least not in the sense that I traditionally interpret the definition of the word: it seems like variables are undefined until after they are declared. In what sense can you “refer to a variable declared later”?
When you use
varit is “hoisted” to the top of the function declaration. Let’s look at the second example again:Notice how
var myvar = 'my value'is declared first. Next, within the function scope,console.log(myvar)is called. The result is “undefined.” Why? You’d think it would be “my value” because that’s the order that the code is in.Because the local variable
var myvarin the function scope is hoisted, it’s not defined. This is essentially equivalent to writing the function like this: