Search code examples
javascriptclosureshoistingself-executing-function

Javascript Hoisting on self executing function


console.log(d, 1);    // undefined 1
var d = 8;
(function() {
  console.log(d, 2);  // undefined 2
  var d = 10
  console.log(d, 3);  // 10 3
})();
console.log(d, 4);    // 8 4

Could anyone please explain how this code produce the commented output ?


Solution

  • Important things to remember

    1. Any variable declared with var, will be undefined before the control reaches the line where it is defined, unless something else is assigned. This is because, in JavaScript, declarations are hoisted.

    2. Any variable declared with var, will be scoped to the function in which it is defined.


    With this understanding, lets look at the code.

    First section

    console.log(d, 1);
    var d = 8;
    

    You access d before the line in which the d declared is executed. So, d will be undefined.

    Mid section

    (function() {
      console.log(d, 2);
      var d = 10;
      console.log(d, 3);
    })();
    

    Same thing here. You access d before and after the d is actually declared. That is why you are getting undefined and 10 respectively.

    Last section

    console.log(d, 4);
    

    Since the variables declared within the functions will not be available outside the functions, in this line d will be the same variable declared at line 2. And the last assigned value is 8.