JavaScript Reference ยท Object
Object.preventExtensions()
Reference for JavaScript Object.preventExtensions(): stop new properties being added to an object while existing ones stay changeable and deletable.
Object.preventExtensions() marks an object as non-extensible: from then on, no new own properties can be added to it. Everything that already exists keeps working as before. You can still change values, delete properties and redefine them.
It is the mildest of the three integrity levels. Object.seal() also forbids deleting and reconfiguring, and Object.freeze() also forbids changing values.
Object.preventExtensions(obj); Object.isExtensible(obj); // false
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.preventExtensions(obj)
| Name | Description |
|---|---|
obj |
The object to make non-extensible. |
Return value: the same object that was passed in (not a copy). A primitive argument is returned unchanged.
Exceptions: none for ordinary objects. Failed attempts to add a property by assignment throw a TypeError only in strict mode (modules and classes are always strict). Object.defineProperty() always throws.
Usage notes
- Permanent. There is no way to make an object extensible again.
- Prototype is locked too. A non-extensible object cannot get a different prototype through
Object.setPrototypeOf(); that call throws aTypeError. Adding properties to its prototype object still works, and the instance sees them. - Shallow. Only the object itself is affected. Nested objects stay extensible.
- Deleting is allowed, but once a property is deleted you cannot add it back. That is a surprising side effect of the lock.
- Check with
Object.isExtensible(). Sealed and frozen objects are also non-extensible, so this check alone does not tell you which level you have. - Typical use: protecting an object from typos such as
config.colour = "red"creating a stray property, while still letting existing settings change. - Strict mode turns silent failures into errors, which is why you usually want to run code that locks objects in a module or with
"use strict".
Browser support
Object.preventExtensions() is available in every browser and JavaScript runtime.