Checking if a key exists in a JavaScript object

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to illustrate the correct way to check whether a particular key exists in an object or not. Before moving on to the correct way let's first examine an incorrect way and see how actually its incorrect.

Way 1: Checking for undefined value (incorrect way)

Due to the volatile nature of JavaScript, we might want to check for the existence of key in an object like this −

const obj = {
name: 'Rahul'


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

These both are incorrect ways. Why?

Because in this case there happens to be no 'fName' key, but suppose there existed a 'fName' which was deliberately set to false or undefined.

Our function should have returned that the key did not exist but actually they did. So in such cases this method fails.

Way 2 − Using the in operator (Correct Way)

The in keyword just introduced in the ES6 checks for an entry in an iterable. Therefore, to check for the existence of key, we can do 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 is −


The difference between Way 2 and Way 3 is just that Way 3 only checks for the property of the Object instance it’s called upon whereas ‘in’ checks for Object instance properties as well as inherited properties (if there are any).

Published on 20-Nov-2020 14:59:59