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:
Object.preventExtensions(obj)| Argument | Description |
|---|---|
obj | The object that new properties cannot be added to |
Returns the object itself (now "closed" for extension).
Example
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
console.log(Object.isExtensible(user)); // falseObject.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,enumerableare left untouched.
Example: attempting to add a new property
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):
Error: Cannot define property x, object is not extensibleDifferences from seal() and freeze()
| Method | Can add | Can delete | Can change | configurable descriptors |
|---|---|---|---|---|
preventExtensions() | No | Yes | Yes | Unchanged |
seal() | No | No | Yes | All configurable: false |
freeze() | No | No | No | All 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
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
| Behavior | Allowed? |
|---|---|
| Adding new properties | No |
| Deleting existing ones | Yes |
| Changing values | Yes |
| Changing descriptors | Yes |
| Check | Object.isExtensible(obj) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.