Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Object preventExtensions() Method

JavaScript Object preventExtensions() Method

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: 

  • obj: This parameter holds the object which must be made non-extensible.

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 neveropen1 = {};
  
Object.preventExtensions(neveropen1);
  
try {
    Object.defineProperty(neveropen1, 'prop1', {
        value: "GFG",
        property1: "Geeksforneveropen",
        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 neveropen = {};
let neveropen0 = Object.preventExtensions(neveropen);
console.log(neveropen0 === neveropen);
  
const neveropen1 = { "prop1": 555 };
Object.preventExtensions(neveropen1);
delete neveropen1.prop1;
console.log(neveropen1.hasOwnProperty("prop1"));
  
const neveropen2 = {};
Object.preventExtensions(neveropen2);
neveropen2.prop2 = 3;
  
console.log(
    neveropen2.hasOwnProperty("prop2")
);
  
const neveropen3 = {};
Object.preventExtensions(neveropen3);
console.log(
    Object.isExtensible(neveropen3)
);


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: 

  • Chrome 6 and above
  • Edge 12 and above
  • Firefox 4 and above
  • Opera 12 and above
  • safari 5.1 and above
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments