Do you want to check if a Key exists in JavaScript? If you are learning JavaScript then you may already know checking a key within an object is a very common task. Especially if you are dealing with dynamic data structures.
Whether you are validating user input or iterating through objects, understanding how to check key existence can help you run code efficiently. Additionally, it can help you prevent errors. Now you have understood the importance of checking key existence, it’s time to understand its usage with practical examples. So read the guide properly to understand how you can check your key existence.
Understanding Objects in JS
As per MDN, “An object is a collection of properties, and a property is an association between a name (or key) and a value”. In case a key’s value contains a function, it is called a method. These key-value pairs are used to store all kinds of data. All complex JavaScript frameworks and libraries are using objects at its core. Before diving into the problem let’s create a simple object –
1 2 3 4 5 6 7 8 |
const favbike = { make: 'Yamaha', model: 'r15', year: 2022, engine: 'vva' }; |
In the example, we have an object favbike which contains make, model, year and engine properties. Let’s see how we can access these properties in an object.
1. Accessing properties in an object
Suppose we want the year of manufacture of our favbike . We can easily access the year property using the dot notation –
1 2 3 |
console.log(favbike.year); //Output: 2022 |
We can also access this property using the bracket notation –
1 2 3 |
console.log(favbike['year']); //Output: 2022 |
If you are familiar with PHP. you might notice that it’s similar to how we access associative arrays in PHP.
Now, what happens in case we access a property that is not defined the object. For instance, if we try to access color property of
favbike object. It would return
undefined –
1 2 3 |
console.log(favbike.color); //Output: undefined |
Here, JavaScript was looking for a key named color in the favbike object but couldn’t find it. This might cause bugs and errors in our code. This makes it very important to provide appropriate checks and validations in our code. Let’s see how we can check if a key exists in an object in JavaScript –
1. Using the ‘if else’ operator
The most common way to provide validation in code is using the if else operator. Same goes for checking if a key exists in our JS code. We can check for existence of a key in JavaScript using the following code –
1 2 3 4 5 |
if (favbike.color !== undefined) { //Do something } |
Here, we check for the existence of color key in our object and proceed with parsing of code only if it exists.
2. Using Object.keys() method
We can also check for our key in an object using the Object.keys() method. Using this method, we get an array containing keys as items in string format. Consider the following code –
1 2 3 4 5 6 7 |
const keys = Object.keys(favbike); //Output: ["make", "model", "year", "engine"] if (keys.includes('year')) { //Do something } |
In the above example, we get an array of keys for our favbike object and check for existence of year key using the includes() method. This method is used to check existence of a particular value in an array. This method is a more modern approach as includes() was added in JavaScript in ES6 version.
Note that there is another method Object.getOwnPropertyNames() which we can use to get keys of an object. The main difference between Object.keys() and Object.getOwnPropertyNames() is that the latter can be used to get keys all properties – enumerable and non-enumerable while the former gets keys to only the enumerable properties.
3. Check if a Key Exists in an Object Using ‘in’ Operator
This method is the most commonly used is using in operator. The in operator checks if a value exists in an object and then returns a Boolean value. It checks if the value we have specified is present or not. Lets understand with an example.
1 2 3 4 5 |
if ('make' in favbike) { console.log('Key "make" exists in favbike object.'); } |
Here we are checking if we have make key in object favbike or not.
4. Check if key Exists in an Object Using the ‘hasOwnProperty()’ Method
Another method to check existence of a key in an object is Object.hasOwnProperty() . This method also checks if an object has key in JavaScript. But the only difference is that it only returns true if the key is associated with a direct property of an object. It ignores any inherited properties. On the other hand in operator considers all inherited properties as well.
Let us understand this with an example, if you create an object using a constructor function or class, that object will inherit properties and methods from the prototype of that constructor or class.
1 2 3 4 5 6 7 8 9 10 |
const favbike = { make: 'Yamaha', model: 'r15', year: 2022, engine: 'vva' }; console.log(favbike.hasOwnProperty('make')); // Output: true |
While there are some other methods, those are probably a derivative of the above-mentioned methods in some way. You can look into other methods such as the for...in loop and the Object.entries method as well.
Why It is Crucial to Exclude Prototype Properties
As you have understood we can use both theoperator and object.hasOwnProperty() to check key existence, it’s time to understand why excluding property matters.
1. Distinguish between properties
Using hasOwnProperty() is crucial when you need to distinguish between properties. For instance, you need to distinguish properties that are explicitly defined on an object versus those that are inherited.
2. Avoiding Conflicts
You might want to ensure that a specific key exists as part of the object itself, it helps in avoiding potential conflicts or overrides from the prototype.
3. Iterating Over Properties
When iterating over an object’s properties (e.g., using for…in), you might accidentally include inherited properties unless you use object.hasOwnProperty() to filter them out.
Wrapping Up
Checking if a key exists in JavaScript objects is essential for efficient programming practices. By using methods like the in operator, hasOwnProperty you can ensure your code handles object properties efficiently and avoids potential runtime errors. Whether you are building any kind of application, mastering these concepts helps you build applications that are robust and error-free. This was all about checking if key exists in JavaScript, I hope you have understood the concept. If you liked this article, we implore you to checkout our blog where we regularly share tips, tricks and gotchas in WordPress and Web Development. See you in the next article!