Can someone pls explain to me why this code below outputs undefined | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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()

29th May 2020, 1:17 PM
Victor Emmanuel
Victor Emmanuel - avatar
1 Answer
+ 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.
29th May 2020, 1:23 PM
Gordon
Gordon - avatar