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 main differences between let
and var
keywords
1. Variable hoisting support
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):
// ONLINE-RUNNER:browser;
a = 1; // variable hosting allows for assigning before declaration
console.log(a); // 1
b = 2; // Uncaught ReferenceError: Cannot access 'b' before initialization
console.log(b); // NEVER PRINTED!!!
var a; // a variable declaration
let b; // b variable declaration
Output:
1
Uncaught ReferenceError: Cannot access 'b' before initialization
Example: 2 (variable hoisting):
// ONLINE-RUNNER:browser;
console.log(a); // undefined
console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
var a = 1; // a variable declaration and definition
let b = 2; // b variable declaration and definition
Output:
undefined
Uncaught ReferenceError: Cannot access 'b' before initialization
Example 3 (normal usage):
// ONLINE-RUNNER:browser;
var a = 1; // a variable declaration and definition
let b = 2; // b variable declaration and definition
console.log(a); // 1
console.log(b); // 2
Output:
1
2
2. The let
keyword variables can be created in different scopes:
let keyword variables | var keyword variables | |
---|---|---|
global scope | yes | yes |
function scope | yes | yes |
curly braces scope | yes | no |
Tips
Use let
keyword instead of var
to avoiding possible errors related with scopes.