How to Check if Key Exists in JavaScript Object/Array

Introduction

An object in JavaScript is an unordered collection of key-value pairs (key: value). Each key is known as a property, and is a string representing a property name. If a non-string is given as the key, its stringified representation will be used. A property's value can be of any data type that fits the property conceptually - a string, a number, an array, or even a function.

An array, on the other hand, is a sorted set of values. Each value is referred to as an element, which is identified by a numerical index. An array can include values of almost any type. For example, it can store items like integers, strings, booleans, functions, etc. JavaScript arrays are also not restricted to a single type, meaning a given array can contain multiple different types within it.

When working in JavaScript, you might at a particular point in time need to determine if a key exists in a given object or array.

In this article, we will see the various methods which we could use to check if a particular key exists in a JavaScript object/array.

Using the in Operator

The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.

Checking an Object

let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
  
'name' in user; // Returns true
'profession' in user; // Returns true
'Daniel' in user; // Returns false because no key like that exists
'Farmer' in user; // Returns false because 'Farmer' is not a key, but a value

Checking an Array

Since we demonstrated that the JavaScript in operator can be used with objects, you may be asking if it can also be used with arrays. In JavaScript, everything is an instance of the Object type (except for primitives), so arrays also support the in operator.

Let's confirm if it's an instance of the Object type using the instanceof operator:

let numbers = [22, 3, 74, 35];
  
numbers instanceof Object // Returns true

Now, back to using the in operator:

let numbers = [12, 33, 14, 45, 6];

// Checking if index 1 is present
1 in numbers; // Returns true
// Checking if index 3 is present
3 in numbers; // Returns true

8 in numbers; // Returns false because the 8 index does exist in the array 
6 in numbers; // Returns false because the 6 index does not exist in the array

This will also return true for method properties on an array type, of which the number array is an instance.

'map' in number; // Returns true because 'map' is a method attribute of the array type

Using the hasOwnProperty() Method

In JavaScript, the hasOwnProperty() function is used to determine whether the object has the supplied property as its own property. This is important for determining if the attribute was inherited by the object rather than being its own.

Checking an Object

let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
let hasKey = user.hasOwnProperty('name'); 
  
if (hasKey) {
    console.log('This key exists.');
} else {
    console.log('This key does not exist.');
}

Checking an Array

You might begin to wonder if this would work for arrays. As we established earlier, an array is actually a prototype (instance) of the Object type, therefore it also has this method available to it.

let number = [12, 33, 14, 45];

// Check if key exists
number.hasOwnProperty(1); // Returns true
number.hasOwnProperty(0); // Returns true
number.hasOwnProperty(7); // Returns false because 7 is not an existing index on the array

Using the Object.key() Method

The static method Object.key generates and returns an array whose components are strings of the names (keys) of an object's properties. This may be used to loop through the object's keys, which we can then use to verify if any match a certain key in the object.

Using with the some() Method

some() is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them.

Using some() for Objects

let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
Object.keys(user).some(key => key === 'name'); // Returns true
Object.keys(user).some(key => key === 'role'); // Returns false

We could also customize this into a reusable function:

const checkKey = (obj, keyName) => {
    let keyExist = Object.keys(obj).some(key => key === keyName);
    console.log(keyExist);
};
  
checkKey(user, 'name'); // Return true

Using some() for an Array

let number = [12, 33, 14, 45];
    
// Check if key exists
number.some(value => value === 1); // Returns true
number.some(value => value === 7); // Returns false

Again, just like with the object, we could also make use of a similar customized reusable function to check a value's existence in an array:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

const checkVal = (arr, val) => {
    let valExist = arr.some(value => value === val);
    console.log(valExist);
};

checkVal(number, 7); // Returns false
checkVal(number, 0); // Returns true

Using the indexOf() Method

JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.

Using indexOf() for an Object

The Object type in JavaScript does not actually support the indexOf method, since its properties/keys do not inherently have indexed positions in the object. Instead, we can get the object's keys as an array and then check the existence of a key using the indexOf method:

let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};

// Check if key exists
Object.keys(user).indexOf('name') // Returns 0
Object.keys(user).indexOf('role') // Returns -1

Keep in mind that JavaScript objects do not always preserve key order, so the index returned may not be as meaningful as in arrays. In this case, the index should primarily be used to determine just the existence of a key.

Here is an example of using this in a utility function:

const checkKey = (obj, keyName) => {
    if (Object.keys(obj).indexOf(keyName) !== -1) {
        console.log('This key exists');
    } else {
        console.log('This key does not exist');
    }
};
  
checkKey(user, 'name'); // Logs 'This key exists'
checkKey(user, 'role'); // Logs 'This key does not exists'

Using indexOf() for an Array

As we saw in the previous example, arrays do support the indexOf method, unlike objects. To use it, pass the value of the item you're looking for to indexOf, which will then return the position of that value if it exists in the array:

let number = [12, 33, 14, 45];
    
// Find position of the item in the array
number.indexOf(14); // Returns 2
number.indexOf(7);  // Returns -1

Conclusion

In this article, we have seen all of the possible ways in which we could check if a key or item exists in a JavaScript object/array. We show how to make use of the in operator, hasOwnProperty() method, and some method. We also saw how JS objects and arrays are similar in that arrays inherit from objects, and thus contain many of the same methods.

Last Updated: September 20th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms