JS: Reflect.set

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Reflect.set(obj, key, val)
  • Set a value to a proprety of object.
  • Return true if success, else false.

🟢 TIP: This function is similar to the syntax obj[key] = val, but in a function form. Function form lets you manipulate expressions at run-time.

const xx = {};
Reflect.set(xx, "p", 3);
console.assert(Object.hasOwn(xx, "p"));
console.assert(xx["p"] === 3);
// example of failed attempt to set property
const xx = {};
Object.preventExtensions(xx);
console.assert(Reflect.set(xx, "p", 3) === false);
console.assert(Object.hasOwn(xx, "p") === false);
Reflect.set(obj, key, val, thisValue)

thisValue is passed as value of this (binding) for Getter Setter Properties.

// apple. has a setter property named color.
// it stores value to color_val.
const apple = {
 color_val: "",
 set color(x) {
  this.color_val = x;
 },
};

// grape. has a property named color_val.
const grape = { color_val: "" };

// set apple.color to green
Reflect.set(apple, "color", "green");

// check
console.assert(apple.color_val === "green");

// set setter method apple.color to red, but on object grape
Reflect.set(apple, "color", "red", grape);

// check
console.assert(grape.color_val === "red");

Difference Between Reflect.Set vs Property Assignment Syntax

Reflect.set(obj, key, val)

is similar to the operator form

obj[key] = val

The difference are:

JavaScript. Access Properties