Skip to content

Instantly share code, notes, and snippets.

@knd
Last active December 10, 2015 18:09
Show Gist options
  • Save knd/4472651 to your computer and use it in GitHub Desktop.
Save knd/4472651 to your computer and use it in GitHub Desktop.
Some code to demonstrate hoisted variable in JavaScript.
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