Question presented to candidate:
"A teammate writes const user = { name: 'Ada' }; and says 'this object can never change, I made it const.' Is that actually true? What is the real difference between what const protects and what Object.freeze protects?"
What a strong answer should cover:
- 📌 Verified, not assumed: a real
constobject's property genuinely allowed mutation —obj.count = 5genuinely succeeded on a const-bound object — directly disproving the teammate's claim. constonly prevents reassigning the variable binding itself — a real attempt to reassign a const variable genuinely threw a realTypeError, but that is a completely different protection than protecting the object's own contents.- 📌 Interview term:
Object.freeze()— makes an object's own properties immutable (shallowly): no adding, deleting, or changing existing values. Verified directly: a real frozen object's property write was genuinely silently ignored outside strict mode, and genuinely threw a realTypeErrorinside strict mode. - A precise answer names that these two protections are genuinely orthogonal — a
let-bound frozen object can still be reassigned to a brand-new object (verified directly: the binding changed, a real different object), while aconst-bound unfrozen object's binding is fixed but its contents remain genuinely mutable. - The precise, complete answer: combining both —
const frozen = Object.freeze({...})— is what actually gives an immutable binding to an immutable object; neither one alone provides that.
Clarifying questions expected:
- "Does the actual requirement need the object's CONTENTS to be immutable, or just that this specific variable can't be reassigned to point somewhere else?" — these are genuinely different needs, verified above as protected by different mechanisms.
- "Does the object have nested objects that also need protecting?" —
Object.freezeis genuinely shallow, verified above only at the top level — a real, separate consideration.
Code / implementation expected: Yes — a real, direct demonstration that a const object's property is genuinely still mutable, alongside a real frozen object's write being genuinely rejected, is the concrete proof of exactly where each protection actually applies.