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