How to Check if Key Exists in JavaScript Object
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 Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with React