\In JavaScript, const is used to declare constant variables. A constant variable means that once a value is assigned, it cannot be changed.
The keyword 'const' is used to declare a variable whose value remains fixed throughout the program.
Example
When should const be used ?
You should use 'const' when:
-
The value should not change
-
You want to protect data from accidental modification
-
You want cleaner and safer code
In modern JavaScript ,'const 'is the default choice unless you know the value must change.
There are certain things which the programmer must ensure while using const otherwise errors may occur-
1 When declaring a variable using 'const', you must assign a value immediately.
2 Once a value is assigned to a 'const' variable, it cannot be changed.
3 You can not re-declare the again in the same scope. Just like let, const is also block scoped.
'const with Objects
common confusion is that 'const' objects can be modified.
This is because 'const' protects the reference, not the internal values.
The object reference stays the same
Changing properties inside the object is allowed
You cannot assign a new object to user.
const with Arrays
Arrays declared with 'const' can also be modified.
an add, remove, or update array elements
You cannot reassign the entire array