Open In App

JavaScript Reflect preventExtensions() Method

JavaScript Reflect.preventExtensions() method in Javascript is used to prevent future extensions to the object which means preventing from adding new properties to the object.

Syntax:



Reflect.preventExtensions( obj )  

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

Return value: This method returns the Boolean value. It returns true for the successful prevention of the extensions. Otherwise, returns false.



Exceptions: A TypeError is an exception given as the result when the target is not an Object.

The below example illustrates the Reflect.preventExtensions() method in JavaScript:

Example 1: In this example, we will prevent the object to get new properties using the Reflect.preventExtensions() method in JavaScript:




const object1 = {};
 
console.log(Reflect.isExtensible(object1));
Reflect.preventExtensions(object1);
console.log(Reflect.isExtensible(object1));
 
const obj = {};
Reflect.preventExtensions(obj);
console.log(
    Reflect.isExtensible(obj)
);
obj.val = 3;
console.log(
    obj.hasOwnProperty("val")
);

Output
true
false
false
false

Example 2: In this example, we will prevent the object to get new properties using the Reflect.preventExtensions() method in JavaScript:




let empty = {}
console.log(Reflect.isExtensible(empty));
console.log(Reflect.preventExtensions(empty));
console.log(Reflect.isExtensible(empty));
 
const obj = { "val1": 3, "val2": 4 };
Reflect.preventExtensions(obj);
console.log(obj.hasOwnProperty("val1"));
delete obj.val1;
console.log(obj.hasOwnProperty("val2"));

Output
true
true
false
true
true

Supported Browsers:

The browsers supported by Reflect.preventExtensions() method are listed below:

We have a complete list of Javascript Reflects methods, to check those go through the JavaScript Reflect Reference article.


Article Tags :