Reading JavaScript Puzzlers!, I was following up until I came across this kind of situation.
The code
var name = "abc";
(function () {
console.log(name);
var name = "xyz";
console.log(name);
}) ();
returns
undefined
xyz
But this one
var name = "abc";
(function () {
console.log(name);
}) ();
returns
abc
I am confused, why is name
undefined is the first code on the first call? I guess this is because of JavaScript hoisting and other reasons. In what do these two pieces of code differ?
This has nothing to do with IIFE, this is just var hoisting as you guessed. You would have the same situation with a classic function.
The fact that you redeclared name
somewhere in the IIFE cancels the global scope of name
within this IIFE. The first time you call name
within your IIFE, it behaves as if it was declared (without initialization) at the top of the current scope (the IIFE here) and is thus undefined
.
You can test the var hoisting concept with this little fiddle by commenting and uncommenting a line.