Checking if a key exists in a JavaScript object

It is our responsibility to show you how to check if a key exists within an object. Let’s first look at an incorrect method and find out why it is wrong before moving onto the correct.

Way 1: Checking for undefined value (incorrect way)

JavaScript’s volatile nature means that we might need to check for key presence in objects like these.

const obj = {
name: 'Rahul'
};
if(!obj['fName']){}

or

if(obj['fName'] === undefined){}

These are both incorrect. Why?

This is because there is no ‘fName’ key in this case. But suppose there was an ‘fName’ that was deliberately set to false, or undefined.

Although our function should have returned false positives, the keys actually existed. In such cases, the method is ineffective.

Way 2 − Using the in operator (Correct Way)

The in keyword, which was just introduced in ES6 is used to check for entry in an iterable. We can check the existence for a key by doing something like:

('fName' in obj);

Way 3 − Using hasOwnProperty() method (Correct Way)

Using the Object.prototype.hasOwnProperty() method, we can determine whether or not an object contains a key.

Its syntax reads –

obj.hasOwnProperty('fName');

Way 2 is different from Way 3. It checks for the property that the object instance it’s called upon has, while Way 3 checks for inherited property.