Thursday, August 1, 2019

javascript - Variable hoisting - "var" with global variable name in function



I was practicing some scenario and find a case:



Here is fiddle



According to closure bar function should have access to var x so I expected to alert 1 and condition get false due to if(!1) but it alerted undefined and condition get true and second alert is with value 10.




var x = 1;
function bar() {
alert(x);
if (!x) {
var x = 10;
}
alert(x);
}
bar();



So I am confused why it is prompting undefined?



According to hoisting in a particular scope you define a variable anywhere it is considered as defined at top always.



If it is due to hoisting effect it still have to alert 10 instead of undefined.


Answer



Hoisting causes a variable to be declared everywhere in the function, not defined.




On the first line of bar, since there is var x on line 3 of the function, the global x is masked and you see the local x (which is undefined since it hasn't been given a value yet).



On line 3 of bar, you have x = 10 which defines the variable. This is not hoisted.



On line 5, you alert it, and it is now defined.



Venn Diagram of the above


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...