Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What is `Object.preventExtensions()` for?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Object.preventExtensions() is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.

const obj = { name: 'John' };
Object.preventExtensions(obj);
obj.age = 30; // This will not work, as the object is not extensible
console.log(obj.age); // undefined

What is Object.preventExtensions() for?

Object.preventExtensions() is a method in JavaScript that is used to prevent new properties from being added to an object. This method is part of the ECMAScript 5 specification and is useful for maintaining the integrity of an object by ensuring that its structure cannot be altered by adding new properties.

Syntax

Object.preventExtensions(obj);
  • obj: The object which should be made non-extensible.

Behavior

  • Once an object is made non-extensible, you cannot add new properties to it.
  • Existing properties can still be modified or deleted.
  • The method returns the object that was passed to it.

Example

const obj = { name: 'John' };
Object.preventExtensions(obj);
obj.age = 30; // This will not work, as the object is not extensible
console.log(obj.age); // undefined
obj.name = 'Jane'; // This will work, as existing properties can be modified
console.log(obj.name); // 'Jane'
delete obj.name; // This will work, as existing properties can be deleted
console.log(obj.name); // undefined

Checking if an object is extensible

You can check if an object is extensible using the Object.isExtensible() method.

const obj = { name: 'John' };
console.log(Object.isExtensible(obj)); // true
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // false

Use cases

  • Immutable object structure: When you want to ensure that the structure of an object remains unchanged, you can use Object.preventExtensions().
  • Security: Preventing extensions can be useful in scenarios where you want to avoid accidental or malicious addition of properties to an object.

Further reading

Edit on GitHub