In this post, I will be describing why we should be vigilant while using const to declare variables.
const variables are mutable.
const countries = ["India","USA","UK"];
countries[1] = "Japan";
console.log(countries);
What do you anticipate from above code? Will it throw error?
Well no, the output is :
[ 'India', 'Japan', 'UK' ]
We can clearly see that countries
variable is altered without causing any exception. This shows that const
can't make variables immutable.
In the same sequence, try to guess the output of the following code:
const myName = "rudra";
myName[0] = "R";
console.log(myName)
Did you guess the output to be Rudra
?
If yes, then unfortunately your Javascript basics are not strong.
The output will be rudra
.
Here is the reason:
In Javascript, all the primitives ( Numbers, Strings, Boolean, BigInt, Symbol, Undefined and Null) are immutable, ie once they are initialised, their value can't be changed, but can only be reassigned. All primitives are stored in call stack.
Whereas, all the reference variables ( Objects, Arrays, Maps, Sets ) are mutable, ie there value can be changed directly from the memory location where they are stored. All references are stored in heap area.
const variables can't be reassigned.
This is the sole purpose of using const
. Once a variable declared using const
, can't be reassigned with other value.
const countries = ["India","USA","UK"];
countries = ["India","USA","UK"];
console.log(countries);
Output:
TypeError: Assignment to constant variable.
Top comments (0)