How To Check If A Key Exists In An Object In JavaScript

You can check if a key exists in an object using the hasOwnProperty method or the in operator.

Let's first take a look at the hasOwnProperty method.

const user = {
    name: 'Jane',
    age: 30,
    city: "Auckland",
    country: "New Zealand"
};
if (user.hasOwnProperty('city')) {
    console.log(`The user object has a "city" property`);
} else {
    console.log(`The user object does not have a "city" property`);
}

In the above example, we created an object user with four properties: name, age, city, and country. We then used the hasOwnProperty method to determine if the user object has a property named city. If it does, we print a message saying that *The user object has a "city" property*. Otherwise, we print a message *The user object does not have a "city" property*.

You can also use the in operator to check if a key exists in an object:

const user = {
    name: 'Jane',
    age: 30,
    city: "Auckland",
    country: "New Zealand"
};
if ("city" in user) {
    console.log(`The user object has a "city" property`);
} else {
    console.log(`The user object does not have a "city" property`);
}

The above works similarly to the previous example if the user object has a property named city. If it does, we print a message saying that *The user object has a "city" property*. Otherwise, we print a message *The user object does not have a "city" property*

One thing we need to keep in mind is hasOwnProperty method returns a boolean indicating whether the object has the specified property as a direct property of the object. It does not check properties inherited from the object's prototype chain. On the other hand, the in operator checks if an object has a property with the given name, including properties inherited from the object's prototype chain.

const person = {
    job: "unknown"
}
const john = Object.create(person);
john.name = "John Foo";
if (john.hasOwnProperty('job')) {
    console.log('hasOwnProperty: john has a "job" property');
} else {
    console.log('hasOwnProperty: john does not have a "job" property');
}
if ('job' in john) {
    console.log('in: john has a "job" property');
} else {
    console.log('in: john does not have a "job" property');
}

In the above code, since hasOwnProperty will return false and print *hasOwnProperty: john does not have a "job" property* since it won't continue looking up the prototype chain. But the in operator will return true and print *in: john has a "job" property* as it'll check for the property on the object and its prototype chain.

And that's it! I hope you enjoyed this post. If you've any queries or feedback, feel free to comment.