Midhun KM
Midhun KM

Reputation: 1717

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 ?

Upvotes: 2

Views: 184

Answers (4)

Thomas
Thomas

Reputation: 3593

Because this is what the Code looks like to the Engine:

var outer_d;
console.log(outer_d, 1);    // undefined 1
outer_d = 8;

(function() {
    var inner_d;
    console.log(inner_d, 2);  // undefined 2
    inner_d = 10
    console.log(inner_d, 3);  // 10 3
})();

console.log(outer_d, 4);    // 8 4

Upvotes: 0

CoderPi
CoderPi

Reputation: 13211

console.log(d, 1); // undefined 1
//// d was not set yet, it has no value, wich is undefined

var d = 8;

(function() {

  console.log(d, 2); // undefined 2
  //// this function does not use the global scope, so there is no variable d set yet

  var d = 10

  console.log(d, 3); // 10 3
  //// now you the local variable d to 10

})();

console.log(d, 4); // 8 4
//// this gives the global variable from above (value 8) as you did not change it with the self executing function

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239513

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.

Upvotes: 3

oleh.meleshko
oleh.meleshko

Reputation: 4795

The reason you have undefined 2 is because of having var d = 10 inside this function.

It means that this variable will be declared in the same scope, but later.

P.S: If you want to output 8 ... everywhere, just remove this inner var d = 10 and you will see.

Upvotes: 0

Related Questions