Tuesday, 19 November 2024

Beyond const: Understanding Mutable Arrays in JavaScript

In JavaScript, using const means that the variable itself cannot be reassigned to a different value. However, if the value is an object or an array, the properties of that object or the elements of that array can still be changed. This is because const only ensures that the reference to the value cannot be changed, but it does not make the value itself immutable.

Example of Mutating an Array Declared with const

 

constWithArray.js

const myArray = [1, 2, 3];

console.log(`myArray : ${myArray}`);

// This is allowed because we're mutating the array's contents, 
// not reassigning the variable.
myArray.push(4); // myArray is now [1, 2, 3, 4]
myArray[0] = 10; // myArray is now [10, 2, 3, 4]
console.log(`myArray : ${myArray}`);

try{
	// However, this is not allowed because it attempts to reassign the entire array.
	myArray = [5, 6, 7]; // Error: Assignment to constant variable.
}catch(error){
	console.log(`Error occurred: ${error.message}`);
}

Output

myArray : 1,2,3
myArray : 10,2,3,4
Error occurred: Assignment to constant variable.

In JavaScript, arrays and objects are reference types. When you declare an array with const, the reference to the array is constant, meaning you cannot assign a new array to that variable. However, the contents of the array itself can still be modified because the const keyword does not make the array immutable.

 

How to make an array truly immutable?

If you want to prevent mutations, you can use methods like Object.freeze() to make the array immutable.

 

completeImmutableArray.js

const myArray = Object.freeze([1, 2, 3]);

console.log(`myArray : ${myArray}`);

try{
	myArray.push(4); 
}catch(error){
	console.log(`Error occurred: ${error.message}`);
}

Output

myArray : 1,2,3
Error occurred: Cannot add property 3, object is not extensible


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment