What is the Reflect.set() method in JavaScript?

The Reflect.set() method can be used to set the value for a property of an object.

Syntax

Reflect.set(target, propertyKey, value, thisArg);

This method returns true if the value of the property is set successfully. Otherwise, it returns false.

Example

Let’s create an object and set a value for an already available property using the Reflect.set method.

let obj = {
    name : "Ram",
    age : 20
};
let isSet = Reflect.set(obj, 'name', 'Raj');

console.log(isSet); // true
console.log(obj.name);//Raj

Now, let’s try to add a new property using the Reflect.set method:

let obj = {
    name : "Ram",
    age : 20
};
let isSet = Reflect.set(obj, 'salary', '100');

console.log(isSet); // true
console.log(obj.salary); // 100

Complete code

let obj = {
name : "Ram",
age : 20
};
console.log("The object is :", obj);
let isUpdated = Reflect.set(obj, 'name', 'Raj');
console.log("-------------------");
console.log("Updating Property")
console.log("isUpdated : ", isUpdated); // true
console.log("The object is :", obj);
console.log("-------------------");
console.log("Adding new Property")
isUpdated = Reflect.set(obj, 'salary', '100');
console.log("isUpdated : ", isUpdated); // true
console.log("The object is :", obj);

Free Resources