JavaScript Object preventExtensions() Method (original) (raw)

Last Updated : 29 May, 2023

The Object.preventExtensions() method in JavaScript is a standard built-in object which prevents new properties from ever being added to an object. This method also prevents reassigning of the object’s prototype.

Syntax:

Object.preventExtensions( obj )

Parameters: This method accepts a single parameter as mentioned above and described below:

Return value: This method returns the object after making it non-extensible.

Below examples illustrate the Object.preventExtensions() method in JavaScript:

Example 1: This example throws a type error as we cannot assign new properties to the object because Object.preventExtensions() method is used.

javascript

let geeks1 = {};

Object.preventExtensions(geeks1);

try {

`` Object.defineProperty(geeks1, 'prop1' , {

`` value: "GFG" ,

`` property1: "Geeksforgeeks" ,

`` property2: "Best platform to learn"

`` });

} catch (error) {

`` console.log(error);

}

Output:

TypeError: Cannot define property prop1, object is not extensible

Example 2: In this example, we will check if we have some properties of the object or not using the Object.hasOwnProperty() method with the Object.preventExtensions() method.

javascript

let geeks = {};

let geeks0 = Object.preventExtensions(geeks);

console.log(geeks0 === geeks);

const geeks1 = { "prop1" : 555 };

Object.preventExtensions(geeks1);

delete geeks1.prop1;

console.log(geeks1.hasOwnProperty( "prop1" ));

const geeks2 = {};

Object.preventExtensions(geeks2);

geeks2.prop2 = 3;

console.log(

`` geeks2.hasOwnProperty( "prop2" )

);

const geeks3 = {};

Object.preventExtensions(geeks3);

console.log(

`` Object.isExtensible(geeks3)

);

Output:

true false false false

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers: The browsers supported by Object.preventExtensions() method are listed below: