Question presented to candidate: "You call Object.freeze() on a config object that has a nested object property. Can you still mutate that nested object? Write a deepFreeze() function that actually fixes this — and make sure it does not infinite-loop on a circular reference."
What a strong answer should cover:
- 📌 Interview term: the real, direct answer to the prompt — verified directly: yes —
Object.freeze()is genuinely shallow. Freezing an object prevents changes to that object's OWN properties, but a NESTED object referenced by one of those properties is genuinely NOT itself frozen and remains fully mutable. - 📌 Interview term:
deepFreeze()— a real, recursive utility that callsObject.freeze()on the top-level object, then recurses into every property value that is itself an object or function, freezing each one too — verified directly to correctly prevent mutation at every nested level, including inside arrays. - 📌 Interview term: the real cycle-safety requirement — a precise answer names that a naive recursive
deepFreeze()would genuinely infinite-loop on a real, self-referential (circular) object — the fix is a realObject.isFrozen(obj)guard at the top of the recursive call: if an object is ALREADY frozen, return immediately rather than recursing into it again — verified directly to correctly terminate on a real cyclic structure. - 📌 Interview term:
Reflect.ownKeys()for full coverage — a precise answer names that iterating withObject.keys()alone would silently skip non-enumerable properties and Symbol-keyed properties;Reflect.ownKeys()(covered in more depth in this bank's own dedicated Proxy/Reflect question) correctly walks every own key, enumerable or not, string or Symbol. - A precise answer names the real, practical use case: freezing a shared configuration object or a Redux-style initial state tree so that an accidental deep mutation anywhere in the object graph genuinely throws (in strict mode) rather than silently corrupting shared state.
Clarifying questions expected:
- None — this is an implementation question; directly writing and demonstrating the recursive fix (including the cycle-safety case) is the strong signal.
Code / implementation expected: Yes — a full, real, recursive deepFreeze() implementation, executed against a nested object, an array, and a genuinely circular structure.