Created
May 6, 2013 20:01
-
-
Save aaronfrost/5527718 to your computer and use it in GitHub Desktop.
Demo that ES6 let scoping still allows for variable hoisting
This file contains hidden or 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
//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 | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the difference in between 1st and 2nd IIFE?