Open In App

JavaScript Reflect preventExtensions() Method

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Obj: This parameter holds the target object and it is used to prevent extensions.

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:

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:

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:

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 42 and above
  • Opera 36 and above
  • Safari 10 and above

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads