“Prevention is better than cure”, a famous quote still holds in Programming Language. Developers can avoid Runtime errors just by checking if the key exists for a specific Object.
If you try to access a property that does not exist in your environment, it will return undefined, which can lead to unexpected behavior or errors.
const obj = { name: 'Alice' }; console.log(obj.age.toString());Output
TypeError: Cannot read properties of undefined (reading 'toString')
We got the TypeError because the key “age” does not exist in the Object. We want to prevent this type of runtime error.
Here are five ways to check If a key exists in JavaScript Object:
- Using the “in” operator
- Direct property access with undefined check
- Using hasOwnProperty()
- Using Object.keys()
- Using Object.prototype.hasOwnProperty.call()
Method 1: Using the “in” operator
The “in” operator in JavaScript returns “true” if a “key” exists in the “Object”. If false, then the key does not exist. It works with inherited properties.
const obj = { name: 'Alice' }; if ('age' in obj) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
The key does not exist
In this code, the else block will be executed since the “age” property does not exist.
You can see that the above code does not throw any TypeError and we properly handled the scenario.
However, there is one flaw in using the “in” operator. If the key exists but its value is “undefined”, it returns true. That means it does not work with a “falsy” value.
const obj = { name: 'Alice', age: undefined }; if ('age' in obj) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
TypeError: Cannot read properties of undefined (reading 'toString')
And we get the error even though the key exists in the Object. This is one scenario where this approach fails.
Method 2: Direct property access with “undefined” check
If you want to check if a property is set to “undefined” and its existence, use the “property_name” == undefined approach.
const obj = { name: 'Alice'}; if (obj.age !== undefined) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
The key does not existThis method doesn’t distinguish between non-existent properties and those set to undefined and by doing that it will solve the problem which was there in the “hasOwnProperty()” and “in” operator.
const obj = { name: 'Alice', age: undefined }; if (obj.age !== undefined) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
The key does not exist
In both cases, it can easily detect whether a property is undefined or exists. It can be used as an advantage.
I would highly recommend this approach because it is really fast and easy to understand.
Method 3: Using hasOwnProperty()
The hasOwnProperty() is a built-in JavaScript method that checks if the Object has the property as its own (not inherited).
const obj = { name: 'Alice' }; if (obj.hasOwnProperty("age")) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
The key does not exist
This approach is ideal when you want to check the Object’s own property and not inherited property.
Method 4: Using Object.keys()
You can use the combination of Object.keys() method with Array.includes() method to verify if the Object has a property. The Object.keys() method returns an array of keys and .includes() method checks if an element exists in the array.
const obj = { name: 'Alice', age: 30 }; if (Object.keys(obj).includes('age')) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
30
Since, the “age” property exists, the “if” condition returns true and logs the output.
I would highly recommend this approach if you want to check for multiple keys. However, this process requires two operations and hence it will take time and memory-intensive for large objects.
Method 5: Using Object.prototype.hasOwnProperty.call()
The Object.prototype.hasOwnProperty.call() is a safe method that works even if the hasOwnProperty() method is overridden on the object. It provides maximum safety for checking own properties.
const obj = { name: 'Alice', age: 30 }; if (Object.prototype.hasOwnProperty.call(obj, 'age')) { console.log(obj.age.toString()); } else { console.log("The key does not exist"); }Output
30
This method can be slower compared to the hasOwnProperty() method but it works well with potentially untrusted objects.