How to Check if a Key Exists in JavaScript Object
In this snippet, we are going to guide you in checking whether a key exists in a JavaScript object or not.
Describing Objects in JavaScript
In JavaScript, objects are applied for storing keyed collections of various data and more complicated entities.
JavaScript objects are included in all aspects of the language, so you need to learn them as soon as you start to study it.
Objects are created with figure brackets {…} and should have a list of properties. Property is known as a “key: value”, in which the key or property name is a string, and the value can be whatever.
/* a JavaScript object */
const car = { type: "BMW", model: "X6", color: "white", price: 2500 };
Let's create a personSalary object which stores the salary of some occupation:
For following along, you can copy and paste the code given above into the console in your browser.
There are several ways of checking if a key exists in the object or not. The first one is to use the key. If you pass in the key to the object, it will return the value if it exists and undefined if the key does not exist.
Let's give it a shot in this example:
When you pass the key “programmer” to the object, it returns the matching value, which is 4000, but if you pass "doctor" since it does not exist as a key in the object, its value will be returned as undefined.
The object may have unique keys, and you might want to check if it already exists before adding one. You can do it by using the in operator, as follows:
Now, let’s check out another example together:
A simpler way: The hasOwnProperty() method!
Let's utilize our first example's object again here:
Please note that hasOwnProperty will only return true for direct properties, not inherited ones:
const salary = {};
example.salary = "2500";
/* hasOwnProperty will only return true for direct properties: */
example.hasOwnProperty("salary"); // returns true
example.hasOwnProperty("leaves"); // returns false
example.hasOwnProperty("toString"); // returns false
example.hasOwnProperty("hasOwnProperty"); // returns false