You use const because you don't want a variable to change.
But JavaScript has a surprise for you. π
const user = {
name: "Rahul"
};
user.name = "Alex";
console.log(user.name);
Output:
Alex
Wait⦠wasn't user declared with const?
Here's the trick.
const prevents you from reassigning the variable. It doesn't make the object itself immutable.
This works:
user.name = "Alex";
But this doesn't:
user = { name: "Sam" };
Why?
Because const keeps the variable bound to the same object, but the object's properties can still change.
Think of it like this:
You can't replace the box, but you can change what's inside it.
Want to prevent accidental changes to an object's top-level properties?
Try:
Object.freeze(user);
Remember, Object.freeze() is shallow. Nested objects can still change unless you freeze them separately.
The takeaway: const doesn't mean "nothing can change." It means "this variable can't be reassigned."
Did you know this already, or did JavaScript trick you too?
Top comments (0)