Problem Statement
Can you modify properties of a const object or elements of a const array? Explain why or why not.
Explanation
Yes, you can modify the properties of a const object and the elements of a const array.
In JavaScript, const only prevents reassignment of the variable, not changes to the object or array it references.
So I can update properties, push or pop from an array, but I can’t make that const variable point to a completely new object or array.
If I really want to make an object immutable, I’d use something like Object.freeze() on it.
Code Solution
SolutionRead Only
// MODIFYING CONST OBJECTS
const person = {
name: 'John',
age: 30
};
// These all work - modifying properties
person.name = 'Jane'; // Change property
person.city = 'New York'; // Add property
delete person.age; // Delete property
console.log(person); // { name: 'Jane', city: 'New York' }
// This fails - reassigning variable
// person = { name: 'Bob' }; // TypeError
// MODIFYING CONST ARRAYS
const numbers = [1, 2, 3];
// These all work - modifying contents
numbers.push(4); // Add element
numbers.pop(); // Remove element
numbers[0] = 10; // Change element
console.log(numbers); // Modified array
// This fails - reassigning variable
// numbers = [5, 6, 7]; // TypeError
// WHY IT WORKS
const obj = { x: 1 };
// obj points to memory location
obj.x = 2; // OK - changing contents
obj.y = 3; // OK - adding to contents
// obj = {}; // Error - trying to point elsewhere
// MAKING TRULY IMMUTABLE
const frozen = Object.freeze({ x: 1, y: 2 });
frozen.x = 10; // Ignored
frozen.z = 3; // Cannot add
delete frozen.y; // Cannot delete
console.log(frozen); // { x: 1, y: 2 } (unchanged)
// SHALLOW FREEZE (only top level)
const nested = Object.freeze({
name: 'John',
address: { city: 'NYC' }
});
// nested.name = 'Jane'; // Cannot change
nested.address.city = 'LA'; // Can change (nested not frozen)
// PRACTICAL EXAMPLE
const shoppingCart = [];
shoppingCart.push({ item: 'Book', price: 10 });
shoppingCart.push({ item: 'Pen', price: 2 });
// But we don't want to accidentally reassign
// shoppingCart = []; // Error! Protected by const