What is the Reflect.has method in JavaScript?

The Reflect.has method is used to check if a property is present in an object or in its prototype chain.

Syntax

Reflect.has(targetObj, propertyKey)

Arguments

targetObj: The object in which the property existence is tested.

propertyKey: The name of the property to be checked for existence in an object.

Return value

This method returns true if the property is present in the object or in its prototype chain. Otherwise, it returns false.

Example

let vehicle = { type : "automobile"};
let car = Object.create(vehicle);
car.name = "Car";
car.wheels = "4";
console.log("The car Object is :", car);
console.log("Has wheels property : ", Reflect.has(car, "wheels"));
console.log("Has type property : ", Reflect.has(car, "type"));
console.log("Has color property : ", Reflect.has(car, "color"));

In the code above:

  • We created a vehicle object with the type property.

  • From the vehicle object, we created a car object with the name and wheels property.

  • Then called the Reflect.has method.

For:

Reflect.has(car, "wheels")

The wheels property is present in the car object. So, true will be returned.

For:

Reflect.has(car, "type")

The type property is present in the prototype chain of the car object (car object is created from the vehicle object, so the properties of vehicle object are available to the car object). So, true will be returned.

For:

Reflect.has(car, "color")

The color property is not present in the car object and its prototype chain. So, false will be returned.

Free Resources