var text = \'outside\';
function logIt(){
console.log(text);
text =\'inside\';
}
logIt(); //prints outside. why?
I thought the
It's the variable declaration that's getting hoisted, not the assignment.
In the first function you're only overriding the value of text
after the call to console.log
, but no other text
is being introduced to the local scope of the function.
In the second case, you are introducing a new text
variable that is local (and initialized to undefined
, as expected), and due to variable hoisting, the actual var text
line is interpreted before the call to console.log
, hence the undefined
.
See MDN