Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Reflect has() Method

JavaScript Reflect has() Method

JavaScript Reflect.has() method in JavaScript is used to check whether the property exists in an object or not. It works like the in operator as a function.

Syntax:

Reflect.has(target, propertyKey) 

Parameters: This method accepts two parameters as mentioned above and described below:

  • target: This parameter is the target object and it looks for the property.
  • propertyKey: This parameter is the name of the property to be checked.

Return value: This method returns a Boolean value which indicates if the target has the property.

Exceptions: A TypeError is an exception given as the result when the target is not an object.

The below examples illustrate the Reflect.has() method in JavaScript:

Example 1: In this example, we will check if the object has the property or not using the Reflect.has() method in JavaScript.

javascript




const object1 = {
    property1: 434
};
  
console.log(Reflect.has(object1, 'property1'));
console.log(Reflect.has(object1, 'property2'));
console.log(Reflect.has(object1, 'toString'));
  
let x = { foo: 1 };
console.log(Reflect.has(x, 'foo'));
console.log('foo' in x);
console.log(Reflect.has(x, 'bar'));
console.log('bar' in x);


Output:

true
false
true
true
true
false
false

Example 2: In this example, we will check if the object has the property or not using the Reflect.has() method in JavaScript.

javascript




// Returns true for properties in
// the prototype chain 
console.log(Reflect.has({ x: 0 }, 'toString'));
  
// Proxy with .has() handler method
let obj = new Proxy({}, {
    has(t, k) { return k.startsWith('neveropen') }
});
console.log(Reflect.has(obj, 'neveropen'));
console.log(Reflect.has(obj, 'geekforgeek'));
  
const val1 = { foo: 123 }
const val2 = { __proto__: val1 }
const val3 = { __proto__: val2 }
  
// The prototype chain is: c -> b -> a
console.log(Reflect.has(val3, 'foo'));


Output:

true
true
false
true

Supported Browsers: The browsers supported by JavaScript Reflect.has() Method are listed below:

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 42 and above
  • Opera 36 and above
  • Safari 10 and above

We have a complete list of Javascript Reflects methods, to check those go through the JavaScript Reflect Reference article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments