So I’m playing around with JavaScript and came across what I think to be an oddity. Is anyone able to explain the following? (i’ve included the alerted values as comments)
Why is the first alert(msg) inside foo() returning undefined and not outside?
var msg = 'outside';
function foo() {
alert(msg); // undefined
var msg = 'inside';
alert(msg); // inside
}
foo();
alert(msg); // outside
Considering these both work fine:
var msg = 'outside';
function foo() {
alert(msg); // outside
}
alert(msg); // outside
and:
var msg = 'outside';
function foo() {
var msg = 'inside';
alert(msg); // inside
}
alert(msg); // outside
What is happening in your first example is the declaration and initlization of msg are being split with the declaration being hoisted to the top of the closure.
Therefore the code you wrote is the same thing as
The second example is not the same. In your second example you have not declared a local variable msg so alert(msg) refers to the global msg.
Here is some further reading on:
Hoisting