Skip to content

Instantly share code, notes, and snippets.

@pthrasher
Created October 6, 2011 19:55
Show Gist options
  • Save pthrasher/1268469 to your computer and use it in GitHub Desktop.
Save pthrasher/1268469 to your computer and use it in GitHub Desktop.
JavaScript scope oddities
/*
* 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