Variable Hoisting in JavaScript_Question about the 2nd Console.log Statement

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';
})();

Because the variable is being “hoisted”. This declares myvar before it’s given a value. Since myvar is within the IIFE’s local scope, it doesn’t need to search for the variable anywhere else.

I think I understand better. I tweaked the code so myvar = 'local value'; within the function is commented out:

/**
 * 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';
})();

and got my value instead of undefined as the output. If I understand correctly, since myvar is within the IIFE’s local scope, it first searches the function before searching the global scope.

1 Like