Global JavaScript Variable Scope: Why doesn't this work?
- by CoryDorning
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