Search code examples
javascriptiifehoisting

Hoisting order with IIFE involved, specific example


I came across this code:

var myVar = 'foo';

(function() {
  console.log('Original value was: ' + myVar);
  var myVar = 'bar';
  console.log('New value is: ' + myVar);
})();

Questions:

  1. Is IIFE hoisted to the top before global myVar? 1a. IF it is, is it executed before global myVar is declared?
  2. In IIFE I get undefined first, and bar second. What is the behind the scenes order of execution in IIFE?

Solution

    1. The IIFE is an expression, not a statement, so no it is not hoisted.
    2. var myVar inside the IIFE is hoisted to the top of the function scope, but the assignment is not. The following is equivalent:

    (function(){
       var myVar;
       console.log('Original value was: '+ myVar);
       myVar = 'bar';
       console.log('New value is: ' + myVar);
    })();