4 Ways to Check If a Key Exists in JavaScript Object

Checking if a key exists in JavaScript object might seem simple but there are four different ways to perform this check. These methods are completely different from each other and are used for different use cases, but they all do the same job. Let’s see them one by one.

TL;DR

  • Checking if a key exists in a JavaScript object helps us find whether or not that object contains a specified property.
  • The in operator is a simple way to check for both own and inherited keys in an object.
  • The hasOwnProperty method is best when we want to check only the object’s own keys not those from its prototype.
  • Using Object.keys with Array.includes lets us check for a key among all enumerable properties which is useful for more advanced needs.
  • For better performance, we can use the in operator or hasOwnProperty when checking for a single key, especially in large objects.
  • When a key is missing, it is good practice to handle it with fallback values or error messages to keep our code reliable.

How to check if a key exists in JavaScript object?

There are many different ways to check existence of a key in a JavaScript object. Each one has its unique use case and advantage.

1. Using the in operator

One of the simplest and widely used methods to check if a particular key exists is using the in operator.

It returns a boolean value which is true if the specified property exists in the given object.

Example code:

const user = { 
  name: 'aditya', 
  age: 23 
};

const checkForName = 'name' in user;
const checkForEmail = 'email' in user;

console.log(checkForName);    // true
console.log(checkForEmail);   // false

2. Using the hasOwnProperty() method

The hasOwnProperty() method takes a key name as its argument and returns true if the object has that key as its own (not inherited). It returns false if it is inherited or doesn’t exist.

Example code:

const user = { 
  name: 'aditya', 
  age: 23 
};

const checkForAge = user.hasOwnProperty('age');
const checkForAddress = user.hasOwnProperty('address');

console.log(checkForAge);      // true
console.log(checkForAddress);  // false

3. Using Object.keys() method

The Object.keys() method returns the keys of an object as a JavaScript array while keeping its corresponding values unchanged. We can check if an object has the specified property by seeing if it is in the returned array.

Example code:

const user = { 
  name: 'aditya', 
  age: 23 
};

const keys = Object.keys(user);

const checkForName = keys.includes('name');
const checkForEmail = keys.includes('email');

console.log(checkForUserName);    // true
console.log(checkForUserEmail);   // false

4. Using Strict Inequality (!== undefined)

If you try to access some value using a key that does not exist, JavaScript returns undefined. We can use this operation with a strict inequality (!==) operator to know whether the specific key is undefined or not. It’s just that this method will fail if the key value itself is undefined.

Example code:

const user = { 
  name: 'aditya', 
  age: 23 
};

const checkIfNameDefined = user['name'] !== undefined;
const checkIfEmailDefined = user['email'] !== undefined;

console.log(checkIfNameDefined);    // true
console.log(checkIfEmailDefined);   // false

Common Mistakes When Checking If a Key Exists in an Object

For developers checking if a specific key exists is easy but there are few common mistakes that can anyway lead to unexpected results.

Confusing Key Existence with Value Checks

Sometimes we check for the presence of a key by seeing if its value is not undefined or not null but this can miss keys that exist with undefined values. You can use in or hasOwnProperty to check for the key itself, not its value.

Example:

user.hasOwnProperty(’email’) returns true even if user.email is undefined.

Using in Operator Without Considering Inherited Properties

The in operator also checks keys from the object’s prototype not just the object’s own keys which can give unexpected results. Use hasOwnProperty or Object.hasOwn for only the object’s own keys.

Example:

‘toString’ in user is true, but user.hasOwnProperty(‘toString’) is false.

Forgetting to Check for Null or Non-Object Values

Trying to check keys on null or non-object values can cause errors in our code. Always check if the value is an object before checking for keys.

Example:

if (user && typeof user === ‘object’) before key checks.

Summary

In short, checking if a key exists in a JavaScript object can be done using several methods. You can choose the one based on your needs:

  • Use the in operator when you have to check for both own and inherited properties.
  • Use hasOwnProperty() when you want to ensure that the key is not inherited.
  • Use Object.keys() when you need a list of all keys or want to perform operations on them.
  • Only use strict inequality if you are okay if an undefined property is treated as not existing. As it doesn’t differentiate between non-existent properties and properties set to undefined.

Reference

https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object

Aditya Gupta
Aditya Gupta
Articles: 499