Let
ES6 allows you to use the let to declare variables inside individual blocks (block scope). Rules apply roughly the same as var.
- Basic rule of thumb, let is only scoped to it's container and below, not outside like JS usually behaves with vars.
- var if not inside a function scope will pollute it's enclosing scope. Example…
var foo = true; if (foo) { var x = 1; // var pollutes outside the if } console.log(x); // 1
var foo = true; if (foo) { // <--- explicit block let x = 1; // let attaches ONLY inside the scope {} } console.log(x); // undefined
for(var i = 0; i < 10; i++ ) { // var will be scoped outside the if statement {} } console.log(i); // 10 for(let v = 0; v < 10; v++ ) { // <--- now explicit block // let is only scoped to this block {} } console.log(v); // error
function foo() { var a = 2; if (a >= 1) { // We are inside a {} so use let to scope it to this block let b = a++; // b only works inside the if {} while (b < 10) { let c = a; // c only works inside the while {} b++; } } } foo();
Explicit block
let (a = 2) { console.log(a); // 2 } console.log(a); // reference error
page revision: 5, last edited: 27 Jan 2018 09:42