To declare variables that are constant, the ‘const‘ keyword is used. These constant variables are block scoped like the variables declared using let but they cannot be reassigned or redeclared. If the constant is an object or an array, its items can be updated or removed. This declaration creates a constant whose scope can be either global or local to the block in which it was declared, but global constants does not become the property of the window object unlike var variables. Also, they need to be initialised with a value during declaration as they can’t be changed later.
Mutating Constant Variables
Attempting to reassign a constant variable throws a TypeError: “Assignment to constant variable”.
- Behaviour of const on String, Number and Boolean:
1 | const demoNumber=1; |
Here, we cannot reassign any value(even the same value) in these variables.
- Behaviour of const on Arrays:
Arrays also throw the same error when we try to reassign it.
1 | const demoArray = [1, 2, 3]; |
However, constant arrays can be mutated i.e its elements can be changed, or elements can be added or removed from a constant array. Functions can also be carried out in constant arrays.
1 | const demoArray = [1, 2, 3]; |
- Behaviour of const on Objects:
Objects also throw TypeError when we try to reassign it.
1 | const demoObject = { key1 : 1, key2 : 2 }; |
Similar to arrays, constant objects can also be mutated i.e properties can be changed, added or deleted.
1 | const demoObject = { key1 : 1, key2 : 2 }; |
- So, in short, variables declared using ‘const’ cannot be reassigned or redeclared, but constant arrays and objects can be mutated but not reassigned.