JavaScript · Senior · Question 21 of 75
How do you deep-freeze an object?
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value && typeof value === "object") deepFreeze(value);
}
return Object.freeze(obj);
}- ✓Correct answer: Recursively freeze nested objects and then the object itself
- 2Call
Object.freeze(obj, { deep: true }) - 3Use
Object.seal, which works all the way down
Explanation
Object.freeze is shallow, and Object.seal only prevents adding and removing properties. Recursion walks the tree; for circular references, keep visited objects in a WeakSet. freeze has no deep option.