A constant variable, as the name suggests, is a variable that holds a value that cannot be changed once it is assigned.
In JavaScript, constant variable are declared using the ‘const’ keyword.
Declaration and initialization
const pi = 3.14159;
Constant must be assigned a value at the time of declaration. Unlike regular variable, which can be declared without initialization, constant variables require an immediate value assignment.
Basic const usage
Constant can be decalared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
// this throws an error
// Uncaught TypeError: Assignment to constant variable
MY_FAV = 20;
// MY_FAV is 7
console.log("my favorite number is: " + MY_FAV);
// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;
// this throws an error too
var MY_FAV = 20;
// this throws an error too
let MY_FAV = 20;
Block Scoping
const x = 1;
function exampleFunction() {
if (true) {
const x = 10;
console.log(x); // Output: 10
}
console.log(x); // Output: 1
}
exampleFunction();
In this example, the ‘const’ variable ‘x’ is declared 2 times outside function and inside function so it output 10 inside if block and output 1 outside if block.
In JavaScript, using the ‘const’ keyword for variable declaration provides an interesting behavior when dealing with complex data types like objects and arrays.
While a constant variable itself cannot be reassigned, the properties or elements of the object or array can still be modified.
For example:
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
The constant reference to the array remains the same, but the array itself can be changed.
Similarly, when dealing with objects:
const person = { name: 'John', age: 30 };
person.age = 31;
console.log(person); // Output: { name: 'John', age: 31 }
In this case, we can update the ‘age’ property of the ‘person’ object, even though ‘person’ is a constant variable. The reference to the object remains unchanged, but the properties of the object can be modified.