Check object has property in JavaScript

In this post, We are going to learn how to Check object has properties in JavaScript with examples. We have mentioned different ways by using the hasOwnProperty() method, ‘in’ operator, Reflect. has() method undefined with each program’s example.

1. hasOwnProperty() to Check object has property in JavaScript


The object.hasOwnProperty() method returns a boolean value(true or False) indicating that check if the object has a specified property. In this JavaScript program, We have checked Empname and Address property contained in the object.

let Employee ={Empname: 'John', salary: 60000,EmpID:1,Dep:'Admin'}
console.log(Employee.hasOwnProperty('Empname'));
console.log(Employee.hasOwnProperty('Address')); 

Output

true
false

2. check object has property using in operator


The in operator can also be used to check if a property exists in an object in Javascript. The ‘Empname’ in Employee returning true because property exists in the object and returning False for ‘Address’ in Employee property does not exist in the Employee object.

let Employee ={Empname: 'John', salary: 60000,EmpID:1,Dep:'Admin'}
console.log('Empname' in Employee);
console.log('Address' in Employee); 

Output

true
false

3. Reflect.has() to check property exist in object


The Reflect.has() method is used to check a property that exists in an object. It works like an in-operator. Let us understand with the below example

  • Reflect. has(Employee,’ Empname’) returning true because this property key exists in the object.
  • Reflect.has(Employee,’ Address’) returning False because this property key does not exist in the object

Syntax

Reflect.has(object, Key)

Parameters

  • object: The target object in which to look for property
  • key: The name of the property we are looking for in the target object.
let Employee ={Empname: 'John', salary: 60000,EmpID:1,Dep:'Admin'}
 

console.log(Reflect.has(Employee,'Empname'));

console.log(Reflect.has(Employee,'Address'));

Output

true
false

4. Comparing with undefined to check object has property


If a property exists in the object it will return true, when it does not exist, it returns undefined. We can check if a property exists in the object by comparing it with undefined. Let us understand with the below example

  • Employee.Empname !== undefined returning true because the property key exists in the object.
  • Employee.address !== undefined returning False because this property key does not exist in the object
let Employee ={Empname: 'John', salary: 60000,EmpID:1,Dep:'Admin'}

console.log(Employee.Empname !== undefined);

console.log(Employee.address !== undefined);

Output

true
false

Summary

In this post, we have learned how to Check object has property in JavaScript with examples by using 4 different ways In this post, by using the hasOwnProperty() method, in operator, Reflect. has() method undefined with each program’s example.