Skip to content

Instantly share code, notes, and snippets.

@flarnie
Last active August 29, 2015 14:07
Show Gist options
  • Save flarnie/f8894f8a2222894da7b7 to your computer and use it in GitHub Desktop.
Save flarnie/f8894f8a2222894da7b7 to your computer and use it in GitHub Desktop.
ES6 Block Scoping
// 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