JavaScript | Reflect.set() Method

The Reflect.set() method in JavaScript is used to set the value of an object property.

Syntax:

Reflect.set(obj, Key, value, receiver) 

Parameters: This method accept 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 successful set.

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



Below examples illustrate the Reflect.set() method in JavaScript:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

"NULL"
"for"
45
567

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

true
"value"
true
"geek4"
true
Array ["geek1"]
true
Object { value: undefined, writable: true, enumerable: true, configurable: true }

Supported Browsers: The browsers supported by JavaScript Reflect.set() Method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.