Skip to main content

What does Object.preventExtensions() do?

Object.preventExtensions() is a built-in JavaScript method that forbids adding new properties to an object, but allows changing and deleting the ones that already exist.

This is the "softest" form of object protection (unlike seal() and freeze()).


Short summary

Syntax:

javascript
Object.preventExtensions(obj)
ArgumentDescription
objThe object that new properties cannot be added to

Returns the object itself (now "closed" for extension).


Example

javascript
const user = { name: 'Tim', age: 25 }; Object.preventExtensions(user); user.city = 'Kyiv'; // will not be added delete user.age; // can be deleted user.name = 'Oleh'; // can be changed console.log(user); // { name: 'Oleh' }

After Object.preventExtensions():

  • new properties cannot be added;
  • old properties can be deleted;
  • existing values can be changed.

Checking whether an object can be extended

javascript
console.log(Object.isExtensible(user)); // false

Object.isExtensible(obj) returns false if new properties cannot be added to the object.


What happens "under the hood"

Object.preventExtensions(obj) does the following:

  • forbids adding new properties (including via Object.defineProperty());
  • existing properties remain changeable and deletable;
  • configurable, writable, enumerable are left untouched.

Example: attempting to add a new property

javascript
const obj = {}; Object.preventExtensions(obj); try { Object.defineProperty(obj, 'x', { value: 1 }); } catch (err) { console.log('Error:', err.message); }

Throws an error (in strict mode):

javascript
Error: Cannot define property x, object is not extensible

Differences from seal() and freeze()

MethodCan addCan deleteCan changeconfigurable descriptors
preventExtensions()NoYesYesUnchanged
seal()NoNoYesAll configurable: false
freeze()NoNoNoAll configurable: false, writable: false

So preventExtensions() is the softest protection option. It just "closes the entrance", but does not interfere with working on what already exists.


Example - checking against prototypes

javascript
const parent = { role: 'user' }; const child = Object.create(parent); Object.preventExtensions(child); child.name = 'Tim'; // will not be added console.log(child.name); // undefined console.log(child.role); // "user" (inherited from the prototype)

preventExtensions() does not affect inherited properties - they remain accessible through the prototype.


SUMMARY

BehaviorAllowed?
Adding new propertiesNo
Deleting existing onesYes
Changing valuesYes
Changing descriptorsYes
CheckObject.isExtensible(obj)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.