What is the difference between Object.freeze, Object.seal and Object.preventExtensions?
preventExtensions blocks adding properties. seal also blocks deleting and reconfiguring, but allows changing values. freeze blocks everything, so values are read-only too. All three are shallow.
Explain it simply
Think of three levels of locking a notice board.
preventExtensions: no new notices can be pinned, but you can replace or remove existing ones.seal: no new notices and no removing, but you can still edit what the existing ones say.freeze: nothing at all. Look, don't touch.
In sloppy mode, forbidden changes fail silently; in strict mode they throw a TypeError. The snippet below uses Reflect.set and Reflect.deleteProperty, which return true or false instead of throwing, so the results are easy to see.
All three are shallow: an object nested inside a frozen object can still change.
Example
const frozen = Object.freeze({ a: 1 });
const sealed = Object.seal({ a: 1 });
const limited = Object.preventExtensions({ a: 1 });
console.log(Reflect.set(frozen, "a", 2)); // Output: false
console.log(Reflect.set(sealed, "a", 2)); // Output: true
console.log(Reflect.set(sealed, "b", 1)); // Output: false
console.log(Reflect.deleteProperty(sealed, "a")); // Output: false
console.log(Reflect.set(limited, "b", 1)); // Output: false
console.log(Reflect.deleteProperty(limited, "a")); // Output: true
const f = Object.freeze({ inner: { x: 1 } });
f.inner.x = 5;
console.log(f.inner.x); // Output: 5What to say in the interview
"preventExtensions stops adding properties, seal also stops deleting and reconfiguring but allows value changes, and freeze makes the object fully read-only. They are shallow, so for a deeply immutable object I freeze recursively or use an immutable data approach."
Common mistakes
- Thinking const makes an object immutable. freeze is the tool for that.
- Expecting freeze to protect nested objects.