var
, let
& const
are the three javascript keywords which are used to define the properties of a variable. Based on the restrictiveness on variable, we choose one of these keywords. In this article I will discuss the difference between var
, let
and const
keywords in JavaScript.
Difference between var
, let
& const
var
1. Variables declared by var
can be redeclared without any issue. Check this code –
var a = 1; var a = 2;
The above code is completely valid.
2. var can be declared and initialized in separate steps. Check the code –
var a; a = 1 // Valid ✔️
3. Values can be reassigned. Check this code –
var a = 1; a = 2; // Valid ✔️
4. They are not bound with scopes. That is, a var
variable value will be same inside and outside the scope. Check this code –
var a = 1 console.log(a) // Output: 1 { console.log(a) // Output: 1 a = 5 console.log(a) // Output: 5 } console.log(a) // Output: 5 a = 6 { console.log(a) // Output: 6 }
In the above code we saw that value of a remained same everywhere if not reassigned to something else.
5. Need not be declared before use. Check the code –
a = 1; var a; // Valid ✔️
The above code is valid.
let & const
let
& const
behave nearly the same except that you can reassign a let
variable but not const
.
1. You can’t redeclare a let
or const
value. Check this code –
let a = 5; let a = 6; // INVALID ❌ const b = 5; const b = 6; // INVALID ❌ const a = 5; // INVALID ❌ let b = 5 // INVALID ❌
In the above code you can see that once a variable is declared using either let
or const
, you can’t redeclare it with in a scope.
2. You can declare a let
variable and initialize it later but not const
. const
variables need to be initialized at the time of declaration. Check the code –
let a; a = 5 // Valid ✔️ const b; // Invalid ❌ b = 6 // Invalid ❌
3. let
values can be reassigned but not const
values. Check the code –
let a = 5 a = 6 // Valid ✔️ const b = 10 b = 11 // Invalid ❌
4. Both let
and const
values are bound to the scope. Check the code –
let a = 6 console.log(a) // Output: 6 { console.log(a) // Output: 6 } { console.log(a) // Invalid ❌ because "a" is initialized // in this scope so it will use that value // But it is declared after console. var allows // it but let doesn't let a = 7 // Valid ✔️ console.log(a) // Output: 7 } console.log(a) // Output: 6 let a = 8 // Invalid ❌ because "a" is already declared // in 1st line
5. Both let
and const
need to be declared before use. Check the code –
a = 5 let a; // Invalid ❌
What should we use – var
, let
or const
?
We should always use const
. But if you need to reassign the value later in the code then you can use let
. There is no general cases where var
should be used.