EN
JavaScript - difference between let and var
4 points
In this article, we would like to explain the difference between let
and var
keywords in JavaScript.
The var
keyword variables support variable hoisting.
The let
keyword variables do not support variable hoisting.
Definition:
Variable hoisting is automatic shifting variable declarations to the top of the source code, making them accessible in the above of the declarations.
Example 1 (variable hoisting):
xxxxxxxxxx
1
a = 1; // variable hosting allows for assigning before declaration
2
console.log(a); // 1
3
4
b = 2; // Uncaught ReferenceError: Cannot access 'b' before initialization
5
console.log(b); // NEVER PRINTED!!!
6
7
var a; // a variable declaration
8
let b; // b variable declaration
Output:
xxxxxxxxxx
1
1
2
Uncaught ReferenceError: Cannot access 'b' before initialization
Example: 2 (variable hoisting):
xxxxxxxxxx
1
console.log(a); // undefined
2
console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
3
4
var a = 1; // a variable declaration and definition
5
let b = 2; // b variable declaration and definition
Output:
xxxxxxxxxx
1
undefined
2
Uncaught ReferenceError: Cannot access 'b' before initialization
Example 3 (normal usage):
xxxxxxxxxx
1
var a = 1; // a variable declaration and definition
2
let b = 2; // b variable declaration and definition
3
4
console.log(a); // 1
5
console.log(b); // 2
Output:
xxxxxxxxxx
1
1
2
2
let keyword variables | var keyword variables | |
---|---|---|
global scope | yes | yes |
function scope | yes | yes |
curly braces scope | yes | no |
Use let
keyword instead of var
to avoiding possible errors related with scopes.