EN
JavaScript - how to use let keyword
1 points
In this article, we would like to show you how to use the let
keyword in JavaScript.
The let
keyword has been introduced to JavaScript in ES2015. There are a few important things that should know for each programmer who wants to use let
keyword.
let
syntax is similar to var
- variable declaration
xxxxxxxxxx
1let a;
2let b;
3let c;
- variable declaration with value assigning
xxxxxxxxxx
1let a = 1;
2let b = 2;
3let c = 3;
- if the variable is not assigned
xxxxxxxxxx
1let a;
2let b;
3
4console.log(a === undefined); // true
5console.log(b === udeffined); // true
Output:
xxxxxxxxxx
1true
2true
- multiple variables declaration with one
let
keywordxxxxxxxxxx
1let a, b, c;
2
3console.log(a === undefined); // true
4console.log(b === undefined); // true
5console.log(c === undefined); // true
Output:
xxxxxxxxxx
1true
2true
3true
- multiple variables declaration with value assigning
xxxxxxxxxx
1let a = 1, b = 2, c = 3;
2
3console.log(a); // 1
4console.log(b); // 2
5console.log(c); // 3
Output:
xxxxxxxxxx
11
22
33
-
multiple variables declaration, some with value assigning
xxxxxxxxxx
1let a, b = 2, c;
2
3console.log(a); // undefined
4console.log(b); // 2
5console.log(c); // undefined
Output:
xxxxxxxxxx
1undefined
22
3undefined
The scope of let
is the nearest enclosing curly brackets.
xxxxxxxxxx
1
let a = 1;
2
3
{ // this brackets create new scope for let keyword variables
4
let a = 2;
5
6
console.log(a); // 2
7
}
8
9
console.log(a); // 1
Output:
xxxxxxxxxx
1
2
2
1
When let
keyword is used with for
loop the scope of variable is for whole for
statement.
xxxxxxxxxx
1
for (let i = 0; i < 5; ++i) {
2
console.log(i);
3
}
4
5
// i variable cannot be used here
6
// var keyword allowed to use variables here
Output:
xxxxxxxxxx
1
0
2
1
3
2
4
3
5
4
The difference has been described here.
- ALWAYS use
let
keyword.