Check if a Key exists in a JavaScript Object

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
8 min

banner

# Table of Contents

  1. Check if a Key exists in an Object using the in Operator
  2. Checking if a key doesn't exist in an object
  3. Check if a Key exists in an Object using Optional Chaining
  4. Check if a Key exists in an Object using Object.hasOwnProperty
  5. Check if a Key exists in an object using Object.keys()
  6. Check if a Key exists in an object using Array.some()
  7. Checking if a partial key exists in an object
  8. Checking if a key exists in an object in a case-insensitive manner
  9. Returning a default value if a key doesn't exist
  10. Checking if a key exists in an object using lodash
  11. Check if an Object contains a Function in JavaScript

# Check if a Key exists in an Object using the in Operator

Use the in operator to check if a key exists in an object, e.g. "key" in myObject.

The in operator will return true if the key is present in the object, otherwise false is returned.

index.js
const person = { name: 'Bobby Hadz', }; console.log('name' in person); // ๐Ÿ‘‰๏ธ true console.log('age' in person); // ๐Ÿ‘‰๏ธ false if ('name' in person) { // ๐Ÿ‘‡๏ธ this runs console.log('key is in contained in object'); }

check if key exists in object

The code for this article is available on GitHub

The syntax used with the in operator is: string in object.

# Checking if a key doesn't exist in an object

If you need to check if a key doesn't exist in an object, wrap the expression in parentheses.

index.js
const person = { name: 'Bobby Hadz', }; console.log(!('age' in person)); // ๐Ÿ‘‰๏ธ true console.log(!('name' in person)); // ๐Ÿ‘‰๏ธ false if (!('age' in person)) { // ๐Ÿ‘‡๏ธ this runs console.log('key is not in object'); }

checking if key does not exist in object

Wrapping the expression in parentheses allows us to evaluate it as a whole.

# Check if a Key exists in an Object using Optional Chaining

Alternatively, you can use the optional chaining (?.) operator.

If the key exists in the object, the optional chaining operator will return the key's value, otherwise, it returns undefined.

index.js
const person = { name: 'Bobby Hadz', }; console.log(person?.name); // ๐Ÿ‘‰๏ธ Bobby Hadz console.log(person?.age); // ๐Ÿ‘‰๏ธ undefined if (person?.name !== undefined) { // the key exists on the object }

check if key exists in object using optional chaining operator

The code for this article is available on GitHub

We used the optional chaining (?.) operator to check if the name and age keys exist in the object.

The name key exists in the object, so person?.name evaluates to Bobby Hadz. The age key doesn't, so the optional chaining operator returns undefined.

This conditional check wouldn't work if you have keys with undefined values in the object.
index.js
const person = { name: undefined, }; console.log(person?.name); // ๐Ÿ‘‰๏ธ undefined if (person?.name !== undefined) { // the `name` key exists, but this never runs }

The name key exists in the object, but the condition in our if statement does not account for the case where the key is set to undefined.

Depending on your use case, you might or might not want to consider a key with an undefined value present.

# Checking if an object has a nested property

You can also use the optional chaining operator to check if an object has a nested property.

index.js
const obj = {a: {b: 'hello'}}; const value = obj?.a?.b; console.log(value); // ๐Ÿ‘‰๏ธ hello if (value !== undefined) { // if this block runs // ๐Ÿ‘‰๏ธ property exists on the object }

checking if object has nested property

If the specified property exists, its value is returned.

If the object's property doesn't exist the optional chaining ?. operator returns undefined.

index.js
const obj = {}; const value = obj?.a?.b?.c; console.log(value); // ๐Ÿ‘‰๏ธ undefined if (value !== undefined) { // if this block runs // ๐Ÿ‘‰๏ธ property exists on the object }

We used the ?. operator to access a nested property that doesn't exist on the object.

When the ?. operator tries to access the a property, it gets an undefined value and short-circuits returning undefined.

# Check if a Key exists in an Object using Object.hasOwnProperty

Alternatively, you can use the Object.hasOwn() method.

The Object.hasOwn method returns true if the key exists in the object, otherwise, false is returned.

index.js
const person = { name: 'Bobby Hadz', }; console.log(Object.hasOwn(person, 'name')); // ๐Ÿ‘‰๏ธ true console.log(Object.hasOwn(person, 'age')); // ๐Ÿ‘‰๏ธ false if (Object.hasOwn(person, 'name')) { // ๐Ÿ‘‡๏ธ this runs console.log('key exists in the object'); }

check if key exists in object using object hasownproperty

The code for this article is available on GitHub

The Object.hasOwn method returns true if the specified property exists in the object.

If the property is inherited or doesn't exist, the method returns false.

The difference between the Object.hasOwn() method and the in operator is that the in operator checks for the key in the object and its prototype chain, whereas the Object.hasOwn() method only checks for the existence of the key directly on the object.

# Check if a Key exists in an object using Object.keys()

Alternatively, you can use the Object.keys() method.

index.js
const person = { name: 'Bobby Hadz', age: 30, }; const keys = Object.keys(person); if (keys.includes('age')) { // ๐Ÿ‘‡๏ธ this runs console.log('The key exists in the object'); } else { console.log('The key does NOT exist in the object'); } console.log(keys.includes('name')); // ๐Ÿ‘‰๏ธ true console.log(keys.includes('another')); // ๐Ÿ‘‰๏ธ false

check if key exists in object using object keys

The Object.keys method returns an array of the object's keys.

index.js
const person = { name: 'Bobby Hadz', age: 30, }; const keys = Object.keys(person); console.log(keys); // ๐Ÿ‘‰๏ธ [ 'name', 'age' ] console.log(keys.includes('name')); // ๐Ÿ‘‰๏ธ true console.log(keys.includes('another')); // ๐Ÿ‘‰๏ธ false

Once we have an array of the object's keys, we can use the Array.includes() method to check if the key exists in the object.

The Array.includes() method returns true if the supplied value is contained in the array and false otherwise.

# Check if a Key exists in an object using Array.some()

Alternatively, you can use the Array.some() method.

index.js
const person = { name: 'Bobby Hadz', age: 30, }; const keys = Object.keys(person); const keyExists = keys.some(key => { return key === 'age'; }); if (keyExists) { // ๐Ÿ‘‡๏ธ this runs console.log('The key exists in the object'); } else { console.log('The key does NOT exist in the object'); }
The code for this article is available on GitHub

The function we passed to the Array.some() method gets called with each element in the array of keys.

If at least one invocation of the callback function returns a truthy value, the some() method returns true, otherwise, false is returned.

On each iteration, we check if the current key is equal to age and return the result.

index.js
const keyExists = keys.some(key => { return key === 'age'; });

The some() function will return true if the key is contained in the object and false otherwise.

You only have to iterate over the array with some() if you need to check for a more complex condition.

# Checking if a partial key exists in an object

For example, you can check if a partial key exists in an object.

index.js
const person = { name: 'Bobby Hadz', age: 30, }; const keys = Object.keys(person); const keyExists = keys.some(key => { return key.includes('ag'); }); if (keyExists) { // ๐Ÿ‘‡๏ธ this runs console.log('The partial key exists in the object'); } else { console.log('The partial key does NOT exist in the object'); }

The some() function will return true if any of the keys in the object contains ag.

# Checking if a key exists in an object in a case-insensitive manner

Similarly, you can use this approach to check if a key exists in an object in a case-insensitive manner.

index.js
const person = { NAME: 'Bobby Hadz', AGE: 30, }; const keys = Object.keys(person); const keyExists = keys.some(key => { const str = 'age'; return key.toLowerCase() === str.toLowerCase(); }); if (keyExists) { // ๐Ÿ‘‡๏ธ this runs console.log('The key exists in the object'); } else { console.log('The key does NOT exist in the object'); }
The code for this article is available on GitHub

We used the some() method to iterate over the array of keys.

On each iteration, we convert the key and the string to lowercase to perform a case-insensitive comparison.

# Returning a default value if a key doesn't exist

You can use the nullish coalescing (??) operator to return a default value if a key doesn't exist.

index.js
const person = { name: 'Bobby Hadz', age: 30, }; const result = person.country ?? 'Example'; console.log(result); // ๐Ÿ‘‰๏ธ Example

If the value to the left of the nullish coalescing operator (??) is equal to null or undefined, the value to the right is returned, otherwise, the value to the left of the operator is returned.

If accessing the key returns undefined, the value to the right is returned.

# Checking if a key exists in an object using lodash

If you use lodash, you can also use the lodash.get() method to check if a key exists in an object.

If you need to install lodash, run the following command from your terminal.

shell
# ๐Ÿ‘‡๏ธ if you need to initialize a package.json file npm init -y npm install lodash # ๐Ÿ‘‡๏ธ only if you use TypeScript npm install --save-dev @types/lodash

Now you can import and use the lodash.get() and lodash.has() methods.

index.js
import _ from 'lodash'; const person = { name: 'Bobby Hadz', address: { country: 'Example', }, a: [{b: {c: 3}}], }; console.log(_.has(person, 'name')); // ๐Ÿ‘‰๏ธ true console.log(_.has(person, 'address.country')); // ๐Ÿ‘‰๏ธ true console.log(_.has(person, 'a[0].b.c')); // ๐Ÿ‘‰๏ธ true console.log(_.get(person, 'name')); // ๐Ÿ‘‰๏ธ Bobby Hadz console.log(_.get(person, 'address.country')); // ๐Ÿ‘‰๏ธ Example console.log(_.get(person, 'a[0].b.c')); // ๐Ÿ‘‰๏ธ 3
The code for this article is available on GitHub

The lodash.has() method checks if a path is a direct property of an object.

Notice that we can check for nested properties and can also access array elements in the path.

The lodash.get() method gets the value at the specified path.

# Check if an Object has a Nested Property using the logical AND (&&) operator

You can also use the logical AND (&&) operator to check if an object has a nested property.

index.js
const obj = {}; if ( obj.a !== undefined && obj.a.b !== undefined && obj.a.b.c !== undefined ) { // if this block runs // ๐Ÿ‘‰๏ธ the a.b.c property exists on the object }

We manually check for the existence of a nested property.

We used the logical AND && operator, so the conditions in the if statement get checked from left to right, one by one.

If any of the conditions evaluates to false, the if block won't run.

In the example above, we explicitly check if each property is equal to undefined. You might see examples online that use only the logical AND && operator, however, this approach is error-prone.

The following example checks if the value of an object's property is truthy.

Truthy values in JavaScript are all values that are not falsy. Falsy values are: false, 0, "", null, undefined, NaN.

Don't write code like this:

index.js
// โ›”๏ธ error-prone code const obj = {a: {b: {c: 0}}}; if (obj && obj.a && obj.a.b && obj.a.b.c) { // ๐Ÿ‘‰๏ธ This never runs // even though the `c` property exists }

We check if a property of an object is truthy, which isn't enough for us to determine whether the property exists.

The a.b.c property is set to 0, which is a falsy value, so even though the property exists, the if block never runs because the condition isn't met.

# Check if an Object contains a Function in JavaScript

You can use the typeof operator to check if an object contains a function.

The typeof operator returns a string that indicates the type of the value. For functions, the operator returns a string containing the word function.

index.js
const obj = { sum: (a, b) => { return a + b; }, }; if (typeof obj.sum === 'function') { // ๐Ÿ‘‡๏ธ this runs console.log('โœ… the sum property points to a function'); } else { console.log( "โ›”๏ธ the sum property DOESN'T point to a function", ); } console.log(typeof obj.sum); // ๐Ÿ‘‰๏ธ "function" console.log(typeof obj.doesNotExist); // ๐Ÿ‘‰๏ธ "undefined"
The code for this article is available on GitHub

We used the typeof operator to check if the sum property of the object points to a function.

The typeof operator returns a string containing the type of the value.

If the equality check in our if statement passes, the property on the object points to a function.

Here are some more examples of using the typeof operator.

index.js
console.log(typeof {}); // ๐Ÿ‘‰๏ธ "object" console.log(typeof []); // ๐Ÿ‘‰๏ธ "object" console.log(typeof null); // ๐Ÿ‘‰๏ธ "object" console.log(typeof (() => {})); // ๐Ÿ‘‰๏ธ "function" console.log(typeof ''); // ๐Ÿ‘‰๏ธ "string" console.log(typeof 0); // ๐Ÿ‘‰๏ธ "number" console.log(typeof NaN); // ๐Ÿ‘‰๏ธ "number" console.log(typeof undefined); // ๐Ÿ‘‰๏ธ "undefined"
Note that the return value of the operator is always wrapped in a string.

The typeof operator returns "function" for both arrow and named functions.

index.js
console.log(typeof (() => {})); // ๐Ÿ‘‰๏ธ function console.log(typeof function () {}); // ๐Ÿ‘‰๏ธ function

Technically, the type of a class is also a function.

index.js
console.log(typeof class A {}); // ๐Ÿ‘‰๏ธ function

Classes are just syntactic sugar for functions in JavaScript.

However, we can't have a class as a property in an object, so our solution works as expected.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev