W3docs

How to Check if a Key Exists in JavaScript Object

This snippet is explaining how to check whether a key exists in a JavaScript object. Examine the solutions given above and choose the most appropriate.

In this snippet, we are going to guide you in checking whether a key exists in a JavaScript object or not.

Describing Objects in JavaScript

In JavaScript, objects are used for storing keyed collections of various data and more complicated entities.

JavaScript objects are included in all aspects of the language, so you need to learn them as soon as you start to study it.

Objects are created with curly braces {…} and should have a list of properties. Properties are defined as key-value pairs, where the key (or property name) is a string, and the value can be anything.

How to Check if a Key Exists in JavaScript Object

/* a JavaScript object */
const car = { type: "BMW", model: "X6", color: "white", price: 2500 };

Let's create a personSalary object which stores the salary of some occupation:

Javascript key exists in the object

javascript— editable

For following along, you can copy and paste the code given above into the console in your browser.

There are several ways of checking if a key exists in the object or not. The first method is to access the key directly. If the key exists, it returns the corresponding value; otherwise, it returns <code>undefined</code>.

Let's give it a shot in this example:

javascript key exists in the object

javascript— editable

When you pass the key “programmer” to the object, it returns the matching value, which is 4000, but if you pass "doctor" since it does not exist as a key in the object, its value will be returned as undefined.

The object may have unique keys, and you might want to check if it already exists before adding one. You can do it by using the <kbd class="highlighted">in</kbd> operator, as follows:

javascript key exists in the object

javascript— editable

Now, let’s check out another example together:

Javascript key exists in the object

javascript— editable

A simpler way: The hasOwnProperty() method!

Info

We read from MDN: The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Let's utilize our first example's object again here:

Javascript key exists in the object

javascript— editable

Please note that <code>hasOwnProperty</code> will only return true for direct properties, not inherited ones:

How to Check if a Key Exists in JavaScript Object

const salary = {};
salary.salary = "2500";

/* hasOwnProperty will only return true for direct properties: */
salary.hasOwnProperty("salary"); // returns true
salary.hasOwnProperty("leaves"); // returns false
salary.hasOwnProperty("toString"); // returns false
salary.hasOwnProperty("hasOwnProperty"); // returns false