0

In javascript variable declaration is hoisted in the top.

But

var v;
v=1;                 ----------------------------
var getValue=(function(v){
return function(){return v;};
})(v);
v=2;              -----------------------------VVV

                                  both are outside function

but results getValue();//1

why this time v=2 is not hoisted at top?

Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68

1 Answers1

1

The reason you are seeing 1 not 2 is not about hoisting, but the closure that you create around getValue with that IIFE - where a local v variable with the value 1 shadows the global v variable.

var v; // hoisted declaration - global variable "v"
v=1; // "1" is assigned to the global
var getValue=(function(v) { // a function with a local "v" variable (parameter)
    return function(){return v;}; // access the local "v" variable
})(v); // passing the value of the global variable - "1" as the time of the call
v=2; // "2" is assigned to the global variable
getValue(); // the local variable still has the value: 1

If you omit that parameter, your getValue will return the global variable - as the time of the call to it:

var v; // hoisted declaration
// v=1; // irrelevant
var getValue = // (function() { can be omitted
    function() { return v; } // access the global variable
// })() 
v = 2; // assign the variable
getValue() // and access it from the closure: 2
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375