Summary: In this tutorial, you will learn different ways to check whether a key exists in an object or not in JavaScript.

There are several ways to check if a key exists in an object in JavaScript:

1. Using the in operator

if ('key' in object) {
  // do something
}

The in operator checks if an object has a property with the specified name. It returns true if the object has the property, and false if it does not.

2. Using the hasOwnProperty() method

if (object.hasOwnProperty('key')) {
  // do something
}

The hasOwnProperty() method is a method of the Object prototype that returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

3. Using the typeof operator

if (typeof object.key !== 'undefined') {
  // do something
}

The typeof operator returns a string that tells you the type of a variable. If the variable is undefined, it will return the string "undefined".

In this example, we are using the !== operator to check if the value of object.key is not equal to the string "undefined". This will return true if object.key is defined, and false if it is not.

4. Using the !== operator

if (object.key !== undefined) {
  // do something
}

This method is similar to the previous one, but instead of using the typeof operator, we are directly checking if object.key is not equal to the undefined value.

This will also return true if object.key is defined, and false if it is not.

Note that these methods will not check the object’s prototype chain, only the object itself. If you want to check the prototype chain as well, you can use the Object.getOwnPropertyDescriptor() method.

if (Object.getOwnPropertyDescriptor(object, 'key')) {
  // do something
}

The Object.getOwnPropertyDescriptor() method returns a property descriptor for an own property (i.e., one that is directly present on the object, rather than inherited) of a given object. If the object does not have the specified property, it returns undefined. In this example, we are using the method to check if the object has the specified property, and the if statement will execute if it does.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply