Methods Mutate
Methods aren’t just for reading data; they can also mutate (change) the properties of their parent object.
Mutating State
const tree = {
height: 256,
color: "green",
cut() {
// Halves the height property
this.height /= 2;
},
};
tree.cut();
console.log(tree.height); // Output: 128
tree.cut();
console.log(tree.height); // Output: 64
The const Illusion
You might be wondering: “Wait, I thought tree was a constant?”
You are correct, but in JavaScript, the const keyword behaves specifically: it only prevents you from reassigning the variable identifier to an entirely new object.
It does not freeze the contents of the object itself. You are completely free to add, remove, or mutate the properties inside a const object.
const user = { name: "John" };
// This is perfectly legal:
user.name = "Jane";
// This throws a TypeError (Attempting to reassign a const variable):
// user = { name: "Bob" };
Do not trust const objects to be immutable. If you truly need an object to be unchangeable, look into Object.freeze().