Created
March 20, 2015 12:37
-
-
Save ncancelliere/8d3dd76de5ee2246e399 to your computer and use it in GitHub Desktop.
Avoid JavaScript Variables Getting Hoisted
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
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