JavaScript Reflect.set() method in JavaScript is used to set the value of an object property. It returns a Boolean value true if the property is successfully set else it returns false.
Syntax:
Reflect.set(obj, Key, value, receiver)
Parameters: This method accepts four parameters as mentioned above and described below:
- Obj: This parameter holds the target object and it is used to set the property.
- Key: This parameter holds the name of the property to be set.
- value: This parameter holds the value to be set.
- Receiver: It is an optional parameter and the value of this is provided for the call to target if a setter is encountered.
Return value: This method returns a Boolean value which indicates whether the property was successfully set.
Exceptions: A TypeError is an exception given as the result when the target is not an Object.
The below examples illustrate the Reflect.set() method in JavaScript:
Example 1: In this example, we will try to set the value of some property in an object and check for the output using Reflect.set() method in JavaScript.
javascript
const object1 = {}; Reflect.set(object1, 'property1' , "NULL" ); console.log(object1.property1); const array1 = [ 'neveropen' , 'valt' , 'neveropen' ]; Reflect.set(array1, 2, 'for' ); console.log(array1[2]); const val1 = {}; const val2 = {}; Reflect.set(val1, 'prop1' , 45); console.log(val1.prop1); Reflect.set(val2, 'prop2' , 567); console.log(val2.prop2); |
NULL for 45 567
Example 2: In this example, we will try to set the value of some property in an object and check for the output using Reflect.set() method in JavaScript.
javascript
let obj1 = {} console.log(Reflect.set(obj1, 'prop' , 'value' )); console.log(obj1.prop); // Initializing an array let arr = [ 'geek1' , 'geek2' , 'geek3' ] console.log(Reflect.set(arr, 2, 'geek4' )); console.log(arr[2]); // It can truncate an array. console.log(Reflect.set(arr, 'length' , 1)); console.log(arr); // With just one argument, propertyKey // and value are "undefined". let obj = {} console.log(Reflect.set(obj)); console.log(Reflect.getOwnPropertyDescriptor( obj, 'undefined' )); |
true value true geek4 true [ 'geek1' ] true { value: undefined, writable: true, enumerable: true, configurable: true }
Supported Browsers:
The browsers are supported by JavaScript Reflect.set() Methods 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.