Skip to content

Instantly share code, notes, and snippets.

@kgates-github
Last active December 13, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgates-github/4943271 to your computer and use it in GitHub Desktop.
Save kgates-github/4943271 to your computer and use it in GitHub Desktop.
When I decided to take JavaScript seriously a while back, I realized that not fully understanding how the language handles variable scope can lead to some forehead-slapping debugging sessions. In JavaScript, a variable declaration (e.g., var foo = 1) at the end of a function will execute when the function is called, and before any code within th…
var foo = 1,
test;
function barOne() {
if (!foo) var foo = 100;
return foo;
}
test = barOne();
console.log(test); // 100
function barTwo() {
(function () {
var foo = 1000;
}());
return foo;
}
test = barTwo();
console.log(test); // 1
function barThree() {
(function () {
foo = 10000;
}());
return foo;
}
test = barThree();
console.log(test); // 10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment