Why is the second code snippet is behaving unexpectedly?
This question is different from Questions on Javascript hoisting, because this question includes an IIFE, a Local scope, and is an attempt to better understand parent scope.
This function outputs correctly
var one = 1;
function sayOne() {
console.log(one); // actually gets the value from the global scope
}
sayOne();
Output:
1
But this one does not.
var one = 1;
function sayDoom() {
console.log(one); // somehow does not get the value from parent scope
var one = 2;
console.log(one);
(function() {
var one = 3;
console.log(one); // displays correctly
})();
}
sayDoom();
Output:
undefined
2
3
Expected:
1
2
3
sayDoom
, you're experiencinghoisting
, where locally declared variables (in a function) are hoisted up. You're seeingundefined
, because the variable is "available" (through hoisting), but it just hasn't been assigned a value yet. Simply, avar
declaration in a function, regardless of where it's placed in the code (top, middle, or bottom of the code block), will always be referenced thanks to hoisting.