Javascript Object.preventExtensions()

The Object.preventExtensions() method prevents new properties from being added to an object.

Example


preventExtensions() syntax

The syntax of the preventExtensions() method is:

Object.preventExtensions(obj)

Here, preventExtensions() is a static method. Hence, we need to access the method using the class name, Object.


preventExtensions() Parameters

The preventExtensions() method takes in:

  • obj - the object which should be made non-extensible

preventExtensions() Return Value

The preventExtensions() method returns obj i.e. the object being made non-extensible.


Notes:

  • Objects to which we can no longer add new properties are called non-extensible objects.
  • The properties of a non-extensible object, in general, may still be deleted.
  • Attempting to add new properties to a non-extensible object will fail, either silently or by throwing a TypeError in strict mode.
  • Properties can still be added to the non-extensible object's prototype.

Example: Javascript Object.preventExtensions()

Output

Smith
Object.defineProperty(obj, "age", {
       ^

TypeError: Cannot define property age, object is not extensible

In the above example, we have used the preventExtensions() method to prevent new properties from being added to the obj object.

First, we created an empty object obj and used the defineProperty() method to add the name property to the object.

// Output: Smith
console.log(obj.name);

The code above gives Smith as an output, which means name has been added to the object.

Then, we made obj non-extensible by using the preventExtensions() method.

Object.preventExtensions(obj);

Finally, we tried to define a new property age on obj, which leads to a TypeError.

Object.defineProperty(obj, "age", {
  value: 26,
});

Recommended Reading: