/

The preventExtensions() Method in JavaScript

The preventExtensions() Method in JavaScript

In JavaScript, the preventExtensions() method is used with the Object object. This method takes an object as an argument and returns the same object. The preventExtensions() method modifies the object, making it unable to accept new properties. However, it still allows for the removal and modification of existing properties.

Here is an example:

1
2
3
4
5
const dog = {}
dog.breed = 'Siberian Husky'
Object.preventExtensions(dog)

dog.name = 'Roger' // TypeError: Cannot add property name, object is not extensible

In this example, we create a new object called dog and assign the property breed with the value 'Siberian Husky'. After calling the preventExtensions() method on the dog object, any attempt to add a new property, like name, will result in a TypeError as the object is no longer extensible.

It’s important to note that the original object is also returned as the result of the preventExtensions() method. This means that dog and myDog refer to the same exact object.

Although new properties cannot be added, existing properties can still be removed:

1
2
3
4
5
6
const dog = {}
dog.breed = 'Siberian Husky'
dog.name = 'Roger'
Object.preventExtensions(dog)
delete dog.name
dog // { breed: 'Siberian Husky' }

In this updated example, we add the property name to the dog object before calling preventExtensions(). After that, we use the delete operator to remove the name property. As a result, the dog object only contains the breed property.

Overall, the preventExtensions() method is useful when you want to make an object non-extensible, preventing the addition of new properties while still allowing modification and removal of existing properties.

tags: [“JavaScript”, “Object object”, “preventExtensions() method”]