Skip to content

Instantly share code, notes, and snippets.

@ncancelliere
Created March 20, 2015 12:37
Show Gist options
  • Save ncancelliere/8d3dd76de5ee2246e399 to your computer and use it in GitHub Desktop.
Save ncancelliere/8d3dd76de5ee2246e399 to your computer and use it in GitHub Desktop.
Avoid JavaScript Variables Getting Hoisted
var scope = "global";
function() {
console.log(scope); // this produces undefined, not "global"
var scope = "local";
console.log(scope); // this produces "local"
}
// JavaScript doesn't use block scope, so what is actually happening is equal to below
function() {
var scope;
console.log(scope); // the variable exisits but is undefined
scope = "local"; // variable is initialized and given a value
console.log(scope);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment