Check if a key exists in an Object in JavaScript


In this article, we will learn how to check if a key exists in a Javascript object.

An object in javascript can be defined as an unordered collection of key-value pairs (key : value). The key is known as the property, it is represented as a string. The value can be of any data-type like a string, number, an array or a boolean and it can be a function too.

So, sometimes while working with objects we need to see programmatically if a particular property exists in an object or not.

And to check if a specific property (i.e key) exits in a JavaScript object we can use two methods provided by Javascript.

  1. The in operator
  2. The hasOwnProperty() method of an object.

So let's see each method with examples.

Method 1 : Using the in operator

The in operator is used to check if a specific key exists in a JavaScript Object. If the key exists in the object it will return true else it will return false.

Syntax:

prop in object

prop: name of the property to check in the object.

Example:

const car = { 
  make: 'Honda', 
  model: 'Accord', 
  year: 1995
};

console.log('model' in car) // true

In the above code, we have a car object and we are checking for the key 'model' in it. Since the object contains the key, it returned true.

We can also use it in a condition too like this.

if ('model' in car){
    console.log('the model property exits in the object')
}

Method 2 : Using hasOwnProperty() method

The hasOwnProperty() method in javascript checks if a specific key or property exits in an object.

If the object contains the specific key it will return true else it will return false.

The difference between the in operator and hasOwnProperty() is that:

The in operator will return true for inherited properties of an object too, whereas the hasOwnProperty() will only return true if the object has the property directly in it.

Read more about inherited properties and the hasOwnProperty function of an object : JavaScript hasOwnProperty() method of an Object

Syntax:

obj.hasOwnProperty(propName)

propName: name of the property/key we are checking in the object.

Example:

const car = { 
  make: 'Honda', 
  model: 'Accord', 
  year: 1995
};

console.log(car.hasOwnProperty('year')) // true

Since the car object has the property 'year', it returns true .


💾 Recommended Articles