JavaScript Object.preventExtensions(obj) method


The Object.preventExtensions(obj) method in JavaScript is used to prevent new properties from being added to an object. However, it does not affect existing properties; they can still be modified or deleted. This method is useful when you want to ensure that an object's structure remains constant, while still allowing changes to its property values.

Syntax:

Object.preventExtensions(obj);

Parameters:

  • obj: The object you want to prevent extensions on. This object is passed by reference.

Return Value:

  • The modified object itself (the same object passed in).

Key Features:

  • Non-Extensible Objects: After an object is passed to Object.preventExtensions(), it becomes non-extensible, meaning no new properties can be added to it.
  • Existing Properties: Existing properties can still be modified or deleted, as long as they are writable.
  • Shallow Prevention: The method only prevents extensions to the object itself and does not affect nested objects.

Example 1: Basic Usage

const obj = { name: 'Alice', age: 30 }; Object.preventExtensions(obj); obj.age = 31; // This will change the age property obj.gender = 'female'; // This will not add the gender property delete obj.name; // This will still delete the name property console.log(obj); // Output: { age: 31 }

In this example, after preventing extensions on obj, you can modify existing properties like age, but attempts to add a new property (gender) are ignored.

Example 2: Checking if an Object is Non-Extensible

You can check if an object is non-extensible using Object.isExtensible():

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

In this case, Object.isExtensible(obj) returns false because the object has been made non-extensible.

Example 3: Nested Objects

const obj = { name: 'Charlie', details: { age: 30 } }; Object.preventExtensions(obj); obj.details.age = 31; // This will change the age property in the nested object console.log(obj); // Output: { name: 'Charlie', details: { age: 31 } } obj.location = 'USA'; // This will not add the location property console.log(obj); // Output: { name: 'Charlie', details: { age: 31 } }

In this example, the nested object details can still be modified because Object.preventExtensions() only affects the top-level object.

Summary:

  • Object.preventExtensions(obj) is a method that prevents new properties from being added to an object while allowing existing properties to be modified or deleted.
  • It makes the object non-extensible but does not impact existing properties.
  • This method is useful in situations where you want to maintain an object's structure while still allowing for changes in its values.