+ 1
Can someone pls explain to me why this code below outputs undefined
var foo = 1 var bar = function(){ console.log(foo) var foo = 2 } bar()
1 Respuesta
+ 7
There are two foo variable,
one in global scope
one in functional scope
JavaScript closures work like this :
when a variable is used, it will look at the functional chain and the prototypical chain.
As the functional scope one exists, the global one won't be reached for using.
For the functional scope one,
foo declared with var keyword is hoisted, so no Reference Error.
Initialization is not hoisted, so console log shows undefined.