Last active
August 29, 2015 14:07
-
-
Save flarnie/f8894f8a2222894da7b7 to your computer and use it in GitHub Desktop.
ES6 Block Scoping
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
// ES6 block scoping ('let' and 'const') | |
// 'let' example | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let | |
if (true) { | |
let foo = 'bar'; | |
} | |
console.log(foo) // raises error: 'foo' is not defined | |
// Also prevents pass-by-reference errors in 'for' loops: | |
var funcs = []; | |
for(let i = 0; i < 5; i++) { | |
funcs.push(function() { console.log(i); }); | |
} | |
funcs.forEach(function(callback) { callback() }); // logs 0 through 4 | |
// 'const' example | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const | |
if (true) { | |
// Use for constants | |
const foo = 'bar'; | |
// Transpiler won't allow redefining foo within this block. | |
} | |
console.log(foo) // raises error: 'foo' is not defined | |
// ES5 compatible syntax transpiled by es6-transpiler | |
// https://github.com/termi/es6-transpiler | |
if (true) { | |
var foo$ = 'foo'; // let and const both get renamed locally | |
} | |
console.log(foo); // outer scope variables retain old name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment