JavaScript(JS) object method - preventExtensions
The preventExtensions()
method is a built-in method of the JavaScript Object
constructor. It prevents new properties from being added to an object, i.e., makes the object non-extensible. However, existing properties can still be modified or deleted.
Here's the syntax:
Object.preventExtensions(obj)Sourceww:w.theitroad.com
where obj
is the object to make non-extensible. This method takes only one argument, which is the object to make non-extensible.
Here's an example that shows how to use the preventExtensions()
method:
const myObj = { prop1: "value1", prop2: "value2" }; console.log(Object.isExtensible(myObj)); // true Object.preventExtensions(myObj); console.log(Object.isExtensible(myObj)); // false myObj.prop1 = "new value"; console.log(myObj); // { prop1: "new value", prop2: "value2" } myObj.prop3 = "value3"; console.log(myObj); // { prop1: "new value", prop2: "value2" }
In this example, we create an object myObj
with two properties prop1
and prop2
. We use the isExtensible()
method to check whether the object is extensible. Since the object is extensible, isExtensible()
returns true
.
Next, we use the Object.preventExtensions()
method to make the object non-extensible. We then use the isExtensible()
method again to check whether the object is extensible. Since we have made the object non-extensible, isExtensible()
now returns false
.
Finally, we try to modify an existing property prop1
and add a new property prop3
to the object. The modification of prop1
is successful, but the addition of prop3
is not allowed since the object is non-extensible. When we log the value of myObj
, we see that it still contains both properties, but the prop3
property is not added.
The preventExtensions()
method is useful for making an object non-extensible. If an object is non-extensible, you cannot add new properties to it, but you can still modify or delete its existing properties.