Global JavaScript Variable Scope: Why doesn't this work?

Posted by CoryDorning on Stack Overflow See other posts from Stack Overflow or by CoryDorning
Published on 2010-04-21T18:03:35Z Indexed on 2010/04/21 18:13 UTC
Read the original article Hit count: 194

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about variable-scope