const
Learn how const introduces immutability in JavaScript and its limitations.
The const
keyword is used to define a variable whose value shouldn’t change.
Difference between let
and const
If you intend to modify the value in a variable, define it using let
; otherwise, define it using const
.
Example
Here’s an example that shows the difference between using let
and const
:
//BROKEN CODE'use strict';let price = 120.25;const tax = 0.825;price = 110.12;tax = 1.25;
Explanation
There’s no issue changing the value of the price
variable. However, since tax
is defined as a constant, we will get a runtime error when we try to modify the value:
tax = 1.25;
So, we get the following error message:
TypeError: Assignment to constant variable.
Reach of const
Before we declare const
as one of the most awesome features in modern JavaScript, let’s understand its limitations.
Limitations of const
Only primitive values, like numbers, and references to objects are protected from change. The actual object that the reference refers to does not receive any protection from the ...