Check if a Key Exists on Object - JavaScript

When working with JavaScript objects, it's common to need to check if a specific key exists within them.

Luckily, JavaScript offers several ways to accomplish this task. Let's look at some of the easiest:

Using hasOwnProperty() Method

One easy way to check if a key exists in an object is by using the hasOwnProperty() method.

Here's how it works:

Example:

let myObject = {
    name: 'Niall',
    age: 32,
    city: 'Dublin'
};

console.log(myObject.hasOwnProperty('name')); // Output: true
console.log(myObject.hasOwnProperty('job')); // Output: false

Simply call myObject.hasOwnProperty('keyName'), replacing 'keyName' with the name of the key you're interested in.

If the key exists in myObject, hasOwnProperty() will return true; if not, it'll return false.

Using the in Operator

Another effective method is employing the in operator. It checks if a specified property exists in an object.

Here's how to use it:

let myObject = {
    name: 'Alice',
    age: 25,
    city: 'London'
};

console.log('name' in myObject); // Output: true
console.log('job' in myObject); // Output: false

Checking for undefined

You can also directly access the property's value and check if it's undefined. If it's undefined, then the key doesn't exist. Here's how you can do it:

let myObject = {
    name: 'Bob',
    age: 35,
    city: 'Paris'
};

console.log(myObject['name'] !== undefined); // Output: true
console.log(myObject['job'] !== undefined); // Outfalse

Now, you have a few ways to check for the existence of keys in JavaScript objects.

Hopefully, you won't have to search for a solution again. 🤞

So, choose the one that best fits your coding style and requirements!

Happy coding! 🎉

JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.