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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Create an RSS Reader in Node
How to Set Up Cron Jobs in Linux
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to deploy a Deno app using Docker
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Setting Up Stylus CSS Preprocessor
