Ever wondered about the different ways to check if a key exists in a JavaScript object? What about performance? If yes, this short article is for you.
How to check if a key exists in JavaScript object?
Here are the 4 most common ways people do this: (Spoiler: use the first one)
1. Key in object
let testObject = { validKey: undefined, validKey2: 'someString' };
const validKeyIsSet = 'validKey' in testObject; // true --> works with undefined!
const validKey2IsSet = 'validKey2' in testObject; // true
const invalidKeyIsSet = 'invalidKey' in testObject; // false
2. Value retrieval (Avoid, unless you wish to skip falsy values)
let testObject = { validKey: false, validKey2: 'someString' };
const validKeyIsSet = testObject['validKey']; // false --> breaks when value is falsy!
const validKey2IsSet = testObject['validKey2']; // true
const invalidKeyIsSet = testObject['invalidKey']; // false
3. Undefined check
let testObject = { validKey: undefined, validKey2: 'someString' };
const validKeyIsSet = testObject['validKey'] !== undefined; // false -> breaks when value is undefined!
const validKey2IsSet = testObject['validKey2'] !== undefined; // true
const invalidKeyIsSet = testObject['invalidKey'] !== undefined; // false
4. hasOwnProperty
let testObject = { validKey: undefined, validKey2: 'someString' };
const validKeyIsSet = testObject.hasOwnProperty('validKey'); // true
const validKey2IsSet = testObject.hasOwnProperty('validKey2'); // true
const invalidKeyIsSet = testObject.hasOwnProperty('invalidKey'); // false
Performance
Bellow you can see how each of these methods compare with one another.
Edge cases
It is important to remember that each of the above methods have their own specific constraints (see comments in the picture above).
Generally speaking you should prefer using Key in object
as it has good performance and will only be unsuitable for cases where you want to ignore keys that exist but are set to undefined
. In such cases you could use Undefined check
.
Value retrieval
is not meant and should not be used for this purpose at all. But you do find people occasionally (mis)using it in production and that’s why it is included here.
Why would I check if a key exists?
Often times you are iterating a JavaScript array and need to keep track of repeated elements.
If you care about writing performant JavaScript, you will probably end up using JavaScript objects as hash maps in order to avoid O(n²) operations. Hopefully the above information will help you chose the methods that best fits your specific needs.
Conclusion
A few good general rules of thumb:
- Avoid
hasOwnProperty
due to worse performance. - If your object values are always truthy, you could use any of the methods above. You should still avoid using
Value retrieval
as tomorrow they may no longer be… - Favor using
Key in object
unless you have a specific reason.