Ir para conteúdo

ES6: the keyword let in examples

01/04/2016

A street with cars parked in both sides

The keyword let allows us creating block scopes in JavaScript. Let’s see some examples.

Block scope

Using var.

var me = 'James Bond';

if(true) {
  var me = 'Chuck Norris';
}

console.log(me);
// Chuck Norris

Using let.

let me = 'James Bond';

if(true) {
  let me = 'Chuck Norris';
}

console.log(me);
// James Bond

Loops

Using var.

for(var i = 0; i < 5; i++) {
  // ...
}

console.log(i);
// 5

Using let.

for(let i = 0; i < 5; i++) {
  // ...
}

console.log(i);
// ReferenceError: i is not defined

Duplidated variables

Using var.

var country = 'Brazil';
//..
//..
//..
var country = 'Belgium';

console.log(country);
// Belgium

Using let.

let country = 'Brazil';
//..
//..
//..
let country = 'Belgium';

console.log(country);
// Duplicate declaration 'country'

Here you can find an JS Bin with the examples.

Do you like it? Did I write something stupid? Do you want to improve? Open an issue mentioning the post and let’s talk about it.

See all the posts