As a JavaScript developer, we often have to check if a particular key exists in a JS object or not. There are a lot of ways to do a javascript check if key exists within the object. Here are the most popular six ways, for your convenience:
Table of Contents
Using the ‘in’ Operator
The ‘in’ operator is the easiest way to determine whether a key is present in a JavaScript object. If the provided key is present in the JS object, the ‘in’ operator always returns true; otherwise, it returns false.
<script>
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log('name' in person); // Output: true
console.log('nick_name' in person); // Output: false
</script>
Output
Code Explanation
In the above code example, we declared an object ‘person’ with name, surname, and age properties.
The first console.log statement returns true because the key ‘name’ exists within the object ‘person’.
On the other hand, the second console.log statement returns false because the key ‘nick_name’ does not exist in the object.
How ‘in’ operator perform with different property value?
If Key exist with a valid value
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log('name' in person);
OUTPUT: TRUE
If Key DOES NOT exist within the object
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log('nick_name' in person);
OUPUT: FALSE
If Key exist with null value in the object
var person = {
name: null,
surname: 'Maloroy',
age: 44
};
console.log('name' in person);
OUPUT: TRUE
If Key exist with undefined value
var person = {
name: undefined,
surname: 'Maloroy',
age: 44
};
console.log('name' in person);
//
//
//
//
//
OUTPUT: TRUE
If Key exist within A object CHAIN
var person = {
name: undefined,
surname: 'Maloroy',
age: 44,
address: {
country: 'Bangladesh',
city: 'Dhaka'
}
};
console.log('city' in person.address);
OUPUT: TRUE
Key points are:
- If the key exists in an object, then the ‘in’ operator returns always true, irrespective of the value (undefined or null).
- The ‘in’ operator also performs well within object chaining.
- Be careful! The in operator matches all object keys, including those in the object’s prototype chain.
Using the ‘hasOwnProperty’ Method
Our second method is ‘hasOwnProperty’. By using this method, we can also do a javascript check to see if a key exists in an object or not. This method returns true if the specified key or property exists as a direct property of the object. Or else return false.
<script>
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person.hasOwnProperty('name'));
console.log(person.hasOwnProperty('nick_name'));
</script>
Output:
Code Explanation – Javascript Check if Key Exists
In the above code example, we declared the same object ‘person’ with name, surname, and age properties.
The first console.log statement returns true because the key ‘name’ exists within the object ‘person’.
And the second console.log statement returns false because the key ‘nick_name’ does not exist in the object.
How ‘hasOwnProperty’ method perform with different property value?
If Key exist with a valid value
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person.hasOwnProperty('name'));
OUTPUT: TRUE
If Key DOES NOT exist within the object
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person.hasOwnProperty('nick_name'));
OUPUT: FALSE
If Key exist with null value in the object
var person = {
name: null,
surname: 'Maloroy',
age: 44
};
console.log(person.hasOwnProperty('name'));
OUPUT: TRUE
If Key exist with undefined value
var person = {
name: undefined,
surname: 'Maloroy',
age: 44
};
console.log(person.hasOwnProperty('name'));
//
//
//
//
OUTPUT: TRUE
If Key exist within A object CHAIN
var person = {
name: undefined,
surname: 'Maloroy',
age: 44,
address: {
country: 'Bangladesh',
city: 'Dhaka'
}
};
console.log(person.address.hasOwnProperty('city'));
OUPUT: TRUE
Using the ‘Object.keys’ Method
The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names. It takes the object as a parameter and returns the supplied object’s string-keyed property names.
Since the Object.keys() static method returns enumerable string-keyed property names, we can use the ‘includes’ method of the array to do a javascript check if key exists (‘name’ and ‘nick_name’ in this case) or not.
<script>
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(Object.keys(person).includes('name'));
console.log(Object.keys(person).includes('nick_name'));
</script>
Code Explanation
The object declaration is the same as earlier. The main point to discuss is that here Object.keys(person) returns enumerable string-keyed property names, and the includes method returns true or false based on key existence.
How ‘Object.keys’ method perform with different property value?
If Key exist with a valid value
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(Object.keys(person).includes('name'));
OUTPUT: TRUE
If Key DOES NOT exist within the object
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(Object.keys(person).includes('nick_name'));
OUPUT: FALSE
If Key exist with null value in the object
var person = {
name: null,
surname: 'Maloroy',
age: 44
};
console.log(Object.keys(person).includes('name'));
OUPUT: TRUE
If Key exist with undefined value
var person = {
name: undefined,
surname: 'Maloroy',
age: 44
};
console.log(Object.keys(person).includes('name'));
//
//
//
//
OUTPUT: TRUE
If Key exist within A object CHAIN
var person = {
name: undefined,
surname: 'Maloroy',
age: 44,
address: {
country: 'Bangladesh',
city: 'Dhaka'
}
};
console.log(Object.keys(person.address).includes('city'));
OUPUT: TRUE
Using the Optional Chaining Operator – An Alternative way of javascript check if key exists
In today’s modern Javascript environment, you can easily use the optional chaining operator to check if a key exists in an object. The ?.
operator, like the .
chaining operator, allows us to safely access chaining properties without getting an error if a property is undefined or null.
<script>
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person?.name);
console.log(person?.nick_name);
</script>
Output
Code Explanation
The object creation part is the same as before. Just to keep in mind that getting value instead of undefined means the key exists.
How ‘Optional Chaining’ operator perform with different property value?
If Key exist with a valid value
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person?.name);
OUTPUT: Shawpnendu
If Key DOES NOT exist within the object
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44
};
console.log(person?.nick_name);
OUPUT: undefined
If Key exist with null value in the object
var person = {
name: null,
surname: 'Maloroy',
age: 44
};
console.log(person?.name);
OUPUT: null
If Key exist with undefined value
var person = {
name: undefined,
surname: 'Maloroy',
age: 44
};
console.log(person?.name);
//
//
//
//
OUTPUT: undefined
If Key exist within A object CHAIN
var person = {
name: undefined,
surname: 'Maloroy',
age: 44,
address: {
country: 'Bangladesh',
city: 'Dhaka'
}
};
console.log(person.address?.city);
OUPUT: Dhaka
Using Undefined or Null
You can directly compare the key value with undefined or null to do a javascript check if key exists. But in this case, you have to be sure that the key won’t have a false value other than undefined or null.
var person = {
name: 'Shawpnendu',
surname: 'Maloroy',
age: 44,
gender: undefined,
address: null
};
console.log(person.name!==undefined);
console.log(person.nick_name!==undefined);
console.log(person.name!==null);
console.log(person.nick_name!==null);
console.log('\n');
console.log(person.gender!==undefined);
console.log(person.address!==undefined);
console.log(person.gender!==null);
console.log(person.address!==null);
Output
Undefined vs. Null – Which one is best as Object Property Initializer
In Javascript, undefined means not defined yet. Not clear, right? The easy answer is that when you declare a variable but it is not initialized, JS considers it undefined.
Where null is a value. This means you have declared a variable and also initialized it with a null value.
Undefined | Null |
---|---|
Undefined is a non primitive type in JavaScript. | Null is a primitive type in JavaScript. |
Undefined means “not defined”. So we declare a variable but do not assign a value to it. | A null is a value. This means you have declared a variable and also initialized it with a null value. |
console.log(typeof rns undefined. | console.log(typeof null) returns an object. |
Undefined properties won’t be serialized by JSON.stringify(). So whenever a property is set to undefined due to server client roundtrip, values simply disappear. | Null properties get serialized by JSON.stringify() and never disappear due to a round trip. |
During arithmetic operations, undefined values are converted to NaN. | During arithmetic operations, null is converted to zero. |
Now the question is: which one should we use while declaring our variables? After analyzing the above comparison, we strongly recommend not using undefined rather than null in every case to avoid false results.
Using Third Party Libraries
If you are working on an enterprise-level application, you can consider using third-party rich libraries such as Lodash or Underscore JS to do a javascript check if key exists. Because these libraries provide a lot more rich methods, not only to check the keys but also other object manipulation inbuilt methods.
Frequent Use Cases of – Javascript Check if Key Exists
Determining whether a specific key exists in an object is a more frequent requirement in JavaScript development. That’s why the question, “How to check if a key exists in a JavaScript object?” comes up every time. Knowing the existence of a key within an object will help us manipulate data based on the presence of that particular key, define conditional tests, and finally dynamically access object properties.
Some more reasons are:
- User Input Validation: Upon submitting a user form, the first duty is to check the presence of all required parameters within the object. If yes, then pass it on for further processing; otherwise, give a prompt to the user for correction.
- Personalized Error Message Preparation: During a run-time error, the developer may be unaware of the reason behind the error. Thus, generating a personalized error message is very critical if you do not check the required keys in the error object.
- Change Management: Considering frequent change management, we have to prepare dynamic objects. Thus, key checking is a mandatory job to avoid static coding.
- Data Manipulation: During the implementation of runtime polymorphism, we are bound to type-check the object as if it’s a key to developing a complex business logic.
- Conditional Checking: Based on key value combinations, most of the time, developers need to modify business logic to meet client requirements.
Best Practices to Check if Key Exists in Object Javascript
Consider Performance
Different ways give you different performance based on the data set, property volume, and environment, which means processing servers. Even in the same scenarios, performance may vary depending on other external issues. To do an accurate javascript check if key exists.
But if you really need performance consideration, then use an optimized method that will meet your requirements.
For example, if your object is a simple object or you need to check the object’s direct property, then the ‘hasOwnProperty’ method will be a great choice over others like the ‘Object.keys’ method.
Choose Appropriate Method
It’s always better to choose the best method while checking the existence of a key. Our easy and generic guideline is to use the ‘in’ operator or ‘hasOwnProperty’ method only if you need to check a single hierarchy property.
If you need to check both direct and inherited properties, then use the ‘Object.keys’ method instead.
The in operator and hasOwnProperty methods are slow but reliable. Direct comparison is the fastest method if you can use undefined and null values properly.
For performance benchmarking check this.
Check the Key Within Nested Objects
You can also do a javascript check if key exists within nested objects. The hasOwnProperty() method returns false always if the property is inherited, or never declared at all. Unlike the in operator, this method does not check for the specified property in the object’s prototype chain.
<script>
const person = {};
person.name = 'Shawpnendu';
console.log(person.hasOwnProperty('name'));
// Output: true
// toString is an inherited property
console.log(person.hasOwnProperty('toString'));
// Output: false
// in operator can check the inherited property
console.log('toString' in person);
// Output: true
// Also unable check the inherited property
// to ensure proper javascript check if key exists
console.log(Object.keys(person).includes('toString'));
// Output: false
</script>
Conclusion
In this article, we have discussed every possible JS built-in workaround, but you can also achieve this by looping through the keys using a for loop to perform a versatile javascript check if key exists.
That part we do not discuss here because our focus is only on object key checking with popular and most-practiced methods and operators.
Though we have also discussed best practices, summarized again:
- Use the in operator for a quick and top-level check only.
- Do not use the hasOwnProperty method for checking inherited properties.
- Use direct comparison only when you are aware of object property initialization.
- For object chaining, use all techniques with additional logical checks.
- Use third-party tool if you are planning for an enterprise level application. These tools will help you to perform a javascript check if key exists, in a very simple ways.
So we have discussed every way to perform a javascript check if key exists. Hope, this article will enrich your knowledge of JS object manipulation.
FAQs
What is a key in JavaScript?
JavaScript class/object property names (not value) are considered as Key. Developers use these keys to perform data and object manipulation based on user requirements. For example var person = { name: ‘Shawpnendu’, age: 45 }; In this example, the keys are name and age.
How to get key-value in JavaScript?
To get key-value pairs, we can use the Object.keys()
, Object.values()
, and Object.entries()
methods.
The Object.keys(obj) method returns an array of all the keys.
The Object.values(obj) method returns an array of all the values.
The Object.entries(obj) method returns an array of the key-value pairs.
How to perform javascript check if key exists and value exists in array?
You can use the includes() method (already discussed earlier) to do a javascript check if key exists in an array. You can also use it to check if a specific part of a string exists within a string. It always returns true if the item exists within an array or string and false otherwise.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply