How to Check if Key Exists in JavaScript Object

Updated onbyAlan Morel
How to Check if Key Exists in JavaScript Object

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:

JAVASCRIPT
const 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:

JAVASCRIPT
const 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:

JAVASCRIPT
const 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:

JAVASCRIPT
const 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:

JAVASCRIPT
const 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.