Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Last active August 29, 2015 14:17
Show Gist options
  • Save MattSurabian/8c19cead9bb389f4f99e to your computer and use it in GitHub Desktop.
Save MattSurabian/8c19cead9bb389f4f99e to your computer and use it in GitHub Desktop.
Example of JS hoisting
// In this case the variable hoisted ends up being declared
// but undefined before the if statement, because it is hoisted
(function(){
try {
if (hoisted) {
var hoisted = true;
console.log("This will not get printed")
}else{
console.log("This will be printed, because hoisted has been declared, but is not set to a truthy value.")
}
}catch(err){
console.log("You might expect a reference error to be caught, but nope! This will never be printed.");
}
})();
// This has a reference error, because the interpreter has no
// idea what "hoist" is
(function(){
try {
if (hoist) {
var hoisted = true;
console.log("This will not get printed, and the if check will throw a reference error.")
}
}catch(err){
console.log(err);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment