Table of Contents
When you have a JavaScript object, sometimes you want to check if a property/key exists on it or not.
In this post, we'll learn the best ways to check if a key exists in an object in JavaScript.
This is the example object we'll be using:
JAVASCRIPTconst object = {
    name: "John",
    age: 30
};
Using the in operator
The easiest way to check if a key exists is to use the in operator. The in operator will return a boolean value representing whether or not the key exists in the object.
Here's an example of how to use the in operator:
JAVASCRIPTconst object = {
    name: "John",
    age: 30
};
const exists = "name" in object;
console.log(exists); // true
That means you can use it in a conditional statement to check if a key exists in an object:
JAVASCRIPTconst object = {
    name: "John",
    age: 30
};
if ("name" in object) {
    console.log("The name property exists in the object");
}
Using hasOwnProperty
Alternatively, you can use the hasOwnProperty method to check if a key exists in an object. The difference between the two is that in will check the prototype chain of the object to see if the key exists, whereas hasOwnProperty will only check the object itself.
Because there are subtle differences, they can return different results, so be aware that you're using the correct method to check if a key exists in an object.
This is how to use hasOwnProperty:
JAVASCRIPTconst object = {
    name: "John",
    age: 30
};
if (object.hasOwnProperty("name")) {
    console.log("The name property exists in the object");
}
Fallback
In the case that your object does not have the key, you can use a fallback value.
The fallback value will be used if the key does not exist in the object, which is useful for when you don't want to use an empty string or null.
Here's how to use a fallback value:
JAVASCRIPTconst object = {
    name: "John",
    age: 30
};
const city = object["city"] || "Unknown";
console.log(city); // Unknown
In this example, since the key city does not exist in the object, the fallback value Unknown will be used.
Conclusion
Knowing how to check if a key exists in an object is a very common task in JavaScript.
Hopefully, this has helped you learned the best ways to check if a key exists in an object.
Thanks for reading and happy coding!
Getting Started with TypeScript
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
Getting Started with Deno
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Learn how to build a Slack Bot using Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
How To Create a Modal Popup Box with CSS and JavaScript
