What does Object.freeze actually guarantee?
The earlier questions in this topic covered how objects are built and how their properties are copied. This answer looks at one special way of marking an object as "do not change me", and it explains exactly how much protection you really get.
Freezing an object makes its own properties non-writable and non-configurable. That means you cannot add a new property, you cannot delete an existing one, and you cannot change the value or the attributes of a property that is already there. The freeze is enforced by the engine, so attempts to break it fail.
const settings = Object.freeze({ theme: 'dark', nested: { font: 'serif' } });
console.log(Object.isFrozen(settings)); // true
console.log(Object.isSealed(settings)); // true
try {
settings.theme = 'light';
} catch (err) {
console.log(err.name); // 'TypeError' in strict mode
}
console.log(settings.theme); // 'dark'
// The freeze is shallow.
settings.nested.font = 'sans';
console.log(settings.nested.font); // 'sans' - the inner object is not frozen
There is a difference between strict mode and sloppy mode here, and it is worth knowing. In strict mode, which includes every ES module and every class body, a failed assignment throws a TypeError, so you find out immediately. In sloppy mode the assignment fails quietly and the object stays unchanged, which is worse, because the code carries on as though it worked.
Freezing also makes the object non-extensible and marks its properties as non-configurable. The isFrozen and isSealed checks report on that state, and the seal method does the weaker version, which prevents additions and deletions but still allows existing values to change.
Two things that freeze does not do are worth pointing out. It does not make the object deeply immutable, because it only touches the top level. And it does not affect the internal state of unusual objects. A frozen date still changes when you call setTime on it, and a frozen array still rejects new elements because the length property is frozen, but the other built-in objects keep their own behaviour.