This post will discuss how to determine whether a key exists in a JavaScript object.

The first solution that comes to mind is to use the strict equality operator to compare the given key’s value with undefined.

Download  Run Code

 
This would have worked in all cases except when the key exists, but its value is actually undefined. This behavior is demonstrated below:

Download  Run Code

 
This post provides an overview of some of the available alternatives to determine whether a key exists in an object correctly.

1. Using hasOwnProperty() method

The hasOwnProperty() method returns true if an object contains the specified property, which is a direct property of that object and not an inherited one. The following example checks if the object obj has a property named two:

Download  Run Code

2. Using In operator

Another approach is to use the in operator, which returns true if the specified property is found in the specified object or its prototype chain. The following example demonstrates.

Download  Run Code

3. Using Reflect.has() method

The static Reflect.has() method allows you to check if a property is in an object. It works like the in operator as a function.

Download  Run Code

4. Using Underscore/Lodash Library

If you’re already using the Underscore or Lodash library, consider using the _.has method, which returns true when the given key is a direct property of the object.

Download Code

5. Using Object.keys() function

Finally, you can iterate over all properties of the object and check each key one by one. This can be easily done using the Object.keys() and Array.prototype.some() method, as shown below:

Download  Run Code

That’s all about checking if a key exists in a JavaScript object.