JavaScript Snippet

Freeze, Seal, and preventExtensions on Objects

Difficulty: Easy

JavaScript ships three integrity levels for objects (`Object.preventExtensions`, `Object.seal`, and `Object.freeze`) and they are easy to confuse because each silently relaxes one rule from the next. This snippet builds them up from least to most restrictive, shows the strict-mode behavior that turns silent failures into errors, and finishes with a recursive `deepFreeze` for nested config. Reach for these when you want a runtime guarantee that downstream code cannot mutate a shared object.

Code Snippets
/

Freeze, Seal, and preventExtensions on Objects

Freeze, Seal, and preventExtensions on Objects

JavaScript ships three integrity levels for objects (`Object.preventExtensions`, `Object.seal`, and `Object.freeze`) and they are easy to confuse because each silently relaxes one rule from the next. This snippet builds them up from least to most restrictive, shows the strict-mode behavior that turns silent failures into errors, and finishes with a recursive `deepFreeze` for nested config. Reach for these when you want a runtime guarantee that downstream code cannot mutate a shared object.

JavaScript
Easy
3 snippets
immutability
references
js-strict-mode

840 views

12

The three calls form a strict ladder of restrictions. preventExtensions blocks new properties only, so existing fields can still be reassigned or deleted. seal adds a no-delete rule on top, but writable values can still change. freeze adds a no-write rule, which is the version most engineers actually want when they say immutable. The matching predicates Object.isExtensible, Object.isSealed, and Object.isFrozen are how you verify the level after the fact, which is handy when an object passes through several layers.