Note of Learn ES6

The let keyword in ES6


var message = "hi";
{
var message = "bye";
}
console.log(message);

Output is bye

var message = "hi";
function greet () {
var message = "bye";
}
console.log(message);

Output is hi

let message = "hi";
{
let message = "bye";
}
console.log(message);

Output is hi

var fs = [];
for (var i = 0; i < 10; i++) {
fs.push(function () {
console.log(i);
}
}
fs.forEach(function (f) {
f();
});

Output is

10
10
10
10
10
10
10
10
10
10

If use let i instead of var i

var fs = [];
for (let i = 0; i < 10; i++) {
fs.push(function () {
console.log(i);
}
}
fs.forEach(function (f) {
f();
});

Output is

0
1
2
3
4
5
6
7
8
9

Keyword let make the variable stay in block.

function varFunc () {
var previous = 0;
var current = 1;
var i;
var temp;
  for(i = 0; i < n; i += 1) {
temp = previous;
previous = current;
current = temp + current;
}
}
function letFunc () {
let previous = 0;
let current = 1;
  for (let i = 0; i < n; i += 1) {
let temp = previous;
previous = current;
current = temp + current;
}
}

In my understanding, keyword let make it easy to use same naming variable in different block. i.e., every block has an independent naming space.


Like what you read? Give ding fan a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.