Javascript Object.preventExtensions()

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

Example

const obj = { x: 1, y: 2 };

// prevent the object from having new properties added to it Object.preventExtensions(obj)
; // try to add a new property to the object obj.z = 3; console.log(obj); // Output: { x: 1, y: 2 }

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()

// create an empty object
let obj = {};

// add a property to the object
Object.defineProperty(obj, "name", {
  value: "Smith",
});

// print object
console.log(obj.name);

// prevent adding of new property to the object
Object.preventExtensions(obj);

// add another property to the object
Object.defineProperty(obj, "age", {
  value: 26,
});

// print object
console.log(obj.age);

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,
});

Also Read:

Did you find this article helpful?