Javascript Object.preventExtensions()

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


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:


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.


  • 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

// prevent adding of new property to the object

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

// print object


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

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.


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

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

Recommended Reading:

Did you find this article helpful?