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.