Open In App

JavaScript Reflect set() Method

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:

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.




const object1 = {};
Reflect.set(object1, 'property1', "NULL");
console.log(object1.property1);
 
const array1 = ['geeks', 'valt', 'geeks'];
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);

Output
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.




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'));

Output
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:

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


Article Tags :