What is Reflect.get() method in JavaScript?
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 thethisvalue for the call to object.
If the property is not present in the object, then
undefinedis 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));