JavaScript · The language round
Does const make an object immutable?
Short answer
No. const prevents reassigning the binding, but the object's properties can still change. Object.freeze() prevents changing own properties, and even that is shallow by default.
const and Object.freeze solve different problems. const is about the variable binding. Object.freeze is about the object's own properties.
const config = { theme: "dark" };
config.theme = "light"; // allowed
console.log(config.theme); // "light"
config = {}; // TypeError: assignment to a constant bindingFreezing an object prevents adding, removing or changing its own properties. In strict mode, a failed write throws; in sloppy mode it is silently ignored.
"use strict";
const config = Object.freeze({
theme: "dark",
nested: { mode: "a" },
});
config.theme = "light"; // TypeError
config.nested.mode = "b"; // allowed: freeze is shallow
console.log(config.nested.mode); // "b"Deep immutability
function deepFreeze(value) {
Object.values(value).forEach((child) => {
if (child && typeof child === "object") deepFreeze(child);
});
return Object.freeze(value);
}Object.seal() prevents adding or removing properties but still allows changing existing values. Object.preventExtensions() only prevents new properties.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between `freeze` and `seal`?
- 2How do you deeply freeze an object?
- 3Does freezing an array prevent `push`?
- 4Why is `const` still useful if the object can change?
Say it in the interview
const only prevents reassigning the variable. The object itself can still be mutated. Object.freeze prevents changing own properties, but it is shallow, so nested objects remain mutable unless I freeze them recursively. Freezing an array stops push and index assignment because those are property writes. const is still useful because it makes the binding stable and communicates intent.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.