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);
}

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.

Further reading

Problem with a question

JavaScript · Senior · question 21

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz