Javascript Constants
A constant in JavaScript is a variable that, once declared, cannot have its value changed. The const keyword is used to declare constants. A constant’s value cannot be altered once it has been declared and given a value.
Syntax:
const name = value;
The name can be any valid identifier and value can be any valid expression. Here’s an example:
const pi = 3.14;
console.log(pi); // output: 3.14
In this example, we have declared a constant pi with the value of 3.14.
Attempting to reassign a constant will result in a syntax error:
const pi = 3.14;
pi = 3.14159; // throws a TypeError: Assignment to constant variable.
It’s important to note that while you cannot reassign a constant, the value it points to can be mutated:
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // output: [1, 2, 3, 4]
In this instance, an array [1, 2, 3] has been defined as the value of the constant arr. The array can still be modified even though we are unable to reassign the arr variable by pushing a new value onto it.