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?