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:
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
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()
:
In this case, Object.isExtensible(obj)
returns false
because the object has been made non-extensible.
Example 3: Nested Objects
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.