Created
October 6, 2011 19:55
-
-
Save pthrasher/1268469 to your computer and use it in GitHub Desktop.
JavaScript scope oddities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This is just a short demo of some of the scoping | |
* oddities in JS that you should watch out for. | |
*/ | |
var x = 1; | |
console.log(x); | |
function foo() { | |
console.log(x); | |
var x = 2; | |
console.log(x); | |
} | |
foo() | |
console.log(x); | |
// Console output: | |
//> 1 | |
//> undefined | |
//> 2 | |
//> 1 | |
/* | |
* The reason for this is that variables | |
* are created (and scoped) at compile | |
* time, but are not assigned until the | |
* particular line is executed. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment