Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

reflect
get
javascript
communitycreator

What is Reflect.get() method in JavaScript?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Reflect.get() method can get the value of a property in an object.

Syntax

Reflect.get(target, propertyKey, thisArg);

Parameters

  • target: the object from which to get the property value.
  • propertyKey: the name of the property.
  • thisArg: (optional) used if encountering a getter; it is the this value for the call to object.

If the property is not present in the object, then undefined is returned.

Example

Let’s use the Reflect.get method to create an object and get the value of the specific property.

let obj = {
    name : "Ram",
    age : 20
};
let name = Reflect.get(obj, 'name');
console.log(name); //Ram
console.log('salary'); //undefined 

Let’s try to get the property of the getter function with a custom this value.

const obj = {
  get name() {
    return  this.name.toUpperCase();
  }
};

let customThisObj = {name: "Ram"};
Reflect.get(obj, 'name',  customThisObj); // "RAM"

In the code above, we passed the customThisObj as the this value for the getter function.


Complete Code

let obj = {
name : "Ram",
age : 20
};
console.log("The object is", obj);
console.log("name is ", Reflect.get(obj, 'name'));
console.log("salary is ", Reflect.get(obj, 'salary'));
// ------------------------
console.log("------------------------\n\n");
console.log("Using Reflect.get with getter function");
obj = {
get name() {
return this.name.toUpperCase();
}
};
let customThisObj = {name: "Ram"};
console.log("Name :", Reflect.get(obj, 'name', customThisObj));

RELATED TAGS

reflect
get
javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring