Javascript is the language of the web. It is a scripting language, i.e. it is not compiled but rather interpreted line by line. In this article, we will be taking a deep dive into what Javascript objects and keys are, and how to check if a key exists in an object. We will discuss various methods to check for key existence in an object.
What are Objects in JavaScript?
Just like we use hashmaps in C++ that store data in the form of “key-value” pairs, We use Javascript object to store data in the same way, i.e. in the form of key-value pairs. So, all in all, Objects are non-primitive data types in Javascript that store an unordered collection of key-value pairs. The association between key-value is called property, so objects are a collection of properties.
For example, we have defined an object “car” with various properties below.
let car = {
name: "WagonR",
model: 2015,
price: 340000
};
Several properties such as name, model, and price are defined for the object “car”. The name, model, and price here indicate the keys, and “WagonR”, 2015 and 340000 are the values corresponding to the related keys.
What are the Keys in JavaScript?
As discussed in the previous section, keys are typically used as the names or the identifiers to access the object’s properties.
Let’s take an example. Say we have an object “student” and the student has several properties like firstName, lastName, rollnumber, and age.
let student = {
firstName:"Joshua",
lastName:"Benz",
rollnumber:2000104,
age:16
};
The keys here are firstName, lastName, rollnumber, and age as they are used to specify the names of the properties which in turn have corresponding values.
How to Check if the Key Exists in an Object?
Now, we know about objects and keys. What if we want to check if a key exists in an object? Taking the previous example only, if we want to check whether the key ‘age’ is present in the object ‘student’ or not, how do we do this? Let’s take a look.
There are several techniques to check if a key exists in an object.
Using the ‘in’ Operator
The best method to check for existing keys is with the use of the ‘in’ operator. It is a simple and easy method to check if an object contains the key. The operator returns a boolean value indicating if a specified key is present in an object. If it returns true, it means that the key exists in the object. If it returns false, it means that the object doesn’t contain that particular key.
Syntax:
The syntax for using the “in” operator is:
‘key’ in object_name;
Let us understand it with the help of an example. We have an object ‘employee’ with certain properties(key-value pairs). We will check if the object employee contains a certain key or not. The code to check using the “in” operator is given below.
//defining an object employee let employee={ empId:2301, name: "Joshua", email:"[email protected]", age:32 }; //both the statements below return true 'name' in employee; 'age' in employee; //below statement returns false 'salary' in employee
Output:
true
true
false
The above code checks if the name and age keys exist in the object ‘employee’ and hence returns true, whereas returns false when checking for the key ‘salary’ as it doesn’t exist in the object.
Using the Inbuilt ‘hasOwnProperty() Method
The second method to check if an object contains a key is by using an inbuilt ‘hasOwnProperty()’ method. The hasOwnProperty() method takes an argument in the string form as the parameter and checks whether that string (the key) is present in the object or not. It returns a boolean value. If it returns true, it means that the key exists in the object. If it returns false, it means that the object doesn’t contain that particular key
Syntax:
The syntax for using this method is as follows:
object_name.hasOwnProperty(‘key_name’)
Let us understand it with the help of the previous example. We have an object ‘employee’ with certain properties(key-value pairs). Now, We will check if the object employee contains a certain key or not using this method. The code for the same is given below.
//defining an object employee let employee={ empId:2301, name: "Joshua", email:"[email protected]", age:32 }; //both the statements below return true console.log(employee.hasOwnProperty('name')); console.log(employee.hasOwnProperty('age')); //below statement returns false console.log(employee.hasOwnProperty('salary'));
Output:
true
true
false
The code above uses the inbuilt method ‘hasOwnProperty(‘key_name’)’ and returns true for the keys – name and age. It returns false when checking for “salary” as the key.
Optional Chaining
Besides the previous techniques, there is also one other method to check if a key exists in an object. But, it’s a relatively new feature introduced in ECMAScript 2020, and may not be supported in all JavaScript environments.
The Optional Chaining method allows you to check if a key exists and access its value in a single line. If a key exists, it returns the value corresponding to the key and If the key does not exist, it returns undefined. The optional chaining operator is ‘?.’ to check if the key exists before accessing its value.
Let’s understand with the help of an example below.
//defining an object employee let employee={ empId:2301, name: "Joshua", email:"[email protected]", age:32 }; //below statement returns Joshua as the name console.log(employee?.name); //below statement returns 32 as the age console.log(employee?.age); //below statement returns undefined console.log(employee?.salary);
Output:
Joshua
32
undefined
In the code above, the optional chaining operator returns the values corresponding to the keys for the keys which are present in the object(such as name and age). It returns undefined for the keys (such as salary) which are not present in the object.
Understanding the Limitations
Let’s discuss the limitations of the above mentioned methods that help us check if a key exists in an object or not.
Let’s use the previous example but explicitly set the property ‘email’ to ‘undefined’ but not delete it from the object.The behavior of the ‘in’ operator and ‘hasOwnProperty()’ method will be different than that of the ‘Optional Chaining’ method.
//defining an object employee with email of the employee as 'undefined' let employee={ empId:2301, name: "Joshua", email:undefined, age:32 }; //below statement uses the 'in' operator to check if the key exist console.log('email' in employee); //below statement uses the hasOwnProperty() to check if object contains the key console.log(employee.hasOwnProperty('email')); //below statement uses the optional chaining method to check if the email exists console.log(employee?.email);
Output:
true
true
undefined
It’s clear from the output that even if ‘email’ property is set to ‘undefined’, the ‘in’ operator method and the ‘hasOwnProperty()’ still return “true”, i.e. the key exists. Whereas, the optional chaining method returns undefined.
Custom Methods to check Key Existence
In certain scenarios, the standard methods may not be sufficient to check for key existence. Let’s take an example.
let employee = { empId:2301, name: "Joshua", email:"[email protected]", age:32, address:{ city:"Tokyo", country:"Japan" } }; //below statement returns false console.log('city' in employee); //below statement returns true console.log('city' in employee.address);
In the code given above, if we check whether the key ‘city’ exists in the employee or not using the ‘in’ operator or any other standard method, it will give the output as false.
But, when we check it to be present in the address property of the employee, it returns true which is somehow contradicting because address is a property of employee and city is a property of address, so indirectly city becomes a property for the employee object as well.
To get the correct output, we need to make a custom function which checks the key existence in nested objects as well. Here’s an example of how you can use Object.keys() and some() to check if a key exists in an object and its nested objects:
let employee = { empId:2301, name: "Joshua", email:"[email protected]", age:32, address:{ city:"Tokyo", country:"Japan" } }; //custom function to check if key exists in an object const checkIfKeyExists = (object, key) => { let keys = Object.keys(object); return keys.some(k => k === key || (typeof object[k] === "object" && checkIfKeyExists(object[k], key))); }; //now below statement will return true console.log(checkIfKeyExists(employee, "city"));
In the code above, the checkIfKeyExists() function recursively checks if a key exists in an object and its nested objects. It uses the Object.keys() method to retrieve all the keys of an object and the some() method to iterate over the keys and check if the specified key exists.
Important Points to Keep in Mind
While checking if a key exists in an object, it becomes important to keep in mind some best practices to ensure efficient and reliable code.
- Use the appropriate method based on your requirements. ‘In’ operator and ‘hasOwnProperty()’ methods are the standard approaches.
- Consider the limitations of both the methods. Note that both the in operator and hasOwnProperty() method may return true for properties explicitly set to ‘undefined’ or not deleted from the object.
- It is necessary to handle edge cases and uncommon conditions as necessary. Depending on your specific use case, you may need to explore alternative methods or custom functions to handle nested objects or specific conditions.
- It is important to test your code thoroughly. Ensure that you test your key existence checks with various scenarios.
- Stay up to date with the latest JavaScript features. Keep an eye on new features like optional chaining that can simplify key existence checks and improve code readability.
By following these best practices, you can write more reliable and efficient code when checking for key existence in JavaScript objects.
Conclusion
In this article, we discussed JavaScript objects and keys. Then, we dwelled further into various methods to check if an object contains a key. The ‘in’ operator and ‘hasOwnProperty()’ method are the standard approaches. Additionally, we discussed the optional chaining method that is used to handle the undefined values. By understanding the available methods and their limitations, one can effectively check for key existence in JavaScript objects and build more robust applications.