Last active
December 10, 2015 18:09
-
-
Save knd/4472651 to your computer and use it in GitHub Desktop.
Some code to demonstrate hoisted variable in JavaScript.
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
function hellKitchen() { | |
if (true) { | |
var knd = "chef"; // will I be chef? | |
} | |
console.log(knd); // yes, I'm a chef due to variable hoisting | |
// and 'knd' is accessible anywhere in 'hellKitchen' | |
} | |
// equivalent snippet of code | |
function hellKitchen101() { | |
var knd; | |
if (true) { | |
knd = "chef"; | |
} | |
console.log(knd); // yes, I'm a chef | |
} | |
// what if | |
function hellKitchen102() { | |
if (false) { | |
var chuckNorris = "chef"; | |
} | |
console.log(chuckNorris); // oops, 'chuckNorris' is 'undefined' | |
// no error raised, why? Tip: 'undefined' != 'not defined' | |
} | |
hellKitchen(); | |
hellKitchen101(); | |
hellKitchen102(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment