I am reading the section on variable hoisting on the following webpage https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting
My question concerns the second console.log statement (console.log(myvar); // undefined
) located in the function toward the bottom of the code segment. Why does myvar
within the console.log statement refer to myvar
in the statement that follows and not to the myvar
in the statement var myvar = 'my value'
above the function header? Thank you for the help.
/**
* Example 1
*/
console.log(x === undefined); // 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';
})();
Because of hoisting, the example above is interpreted as
/**
* Example 1
*/
var x;
console.log(x === undefined); // true
x = 3;
/**
* Example 2
*/
var myvar = 'my value';
(function() {
var myvar;
console.log(myvar); // undefined
myvar = 'local value';
})();