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.
Introduction
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.
1. let
keyword syntax example
let
syntax is similar to var
- variable declaration
let a; let b; let c;
- variable declaration with value assigning
let a = 1; let b = 2; let c = 3;
- if the variable is not assigned
let a; let b; console.log(a === undefined); // true console.log(b === udeffined); // true
Output:
true true
- multiple variables declaration with one
let
keywordlet a, b, c; console.log(a === undefined); // true console.log(b === undefined); // true console.log(c === undefined); // true
Output:
true true true
- multiple variables declaration with value assigning
let a = 1, b = 2, c = 3; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3
Output:
1 2 3
-
multiple variables declaration, some with value assigning
let a, b = 2, c; console.log(a); // undefined console.log(b); // 2 console.log(c); // undefined
Output:
undefined 2 undefined
2. let
keyword scope example
The scope of let
is the nearest enclosing curly brackets.
let a = 1;
{ // this brackets create new scope for let keyword variables
let a = 2;
console.log(a); // 2
}
console.log(a); // 1
Output:
2
1
3. let
keyword with for
loop
When let
keyword is used with for
loop the scope of variable is for whole for
statement.
for (let i = 0; i < 5; ++i) {
console.log(i);
}
// i variable cannot be used here
// var keyword allowed to use variables here
Output:
0
1
2
3
4
4. Difference between let
and var
keywords
The difference has been described here.
5. Tips
- ALWAYS use
let
keyword.