Skip to content

Instantly share code, notes, and snippets.

@aaronfrost
Created May 6, 2013 20:01
Show Gist options
  • Save aaronfrost/5527718 to your computer and use it in GitHub Desktop.
Save aaronfrost/5527718 to your computer and use it in GitHub Desktop.
Demo that ES6 let scoping still allows for variable hoisting
//For more reading, check here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Scope_Cheatsheet#let
//Try running these in the Scratchpad of Mozilla Firefox
//THIS IS NOT WHAT HAPPENS, BUT WHAT YOU ARE EXPECTING
(function(){
if(navigator){
console.log(b); //if let didn't hoist, this would throw an error #THIS IS NOT WHAT ACTUALLY HAPPENS
let b = 1;
console.log(b); //this would log a 1, if line 6 didn't throw an error #THIS IS TRUE
}
console.log(b); //this would throw an error because b didn't get blocked by the block scope #THIS IS TRUE
})()
(function(){
if(navigator){
console.log(b); // undefined, because the 'let b' was hoisted to the top of the if block.
let b = 1;
console.log(b); // 1
}
console.log(b); // throws error
})()
@nightire
Copy link

What's the difference in between 1st and 2nd IIFE?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment