How to check if a key exists in an object in javascript

If some property with a given key is accessed in the object and it is not present, then an error is raised. Thus before accessing the property, it is recommended to check if a property with that key is present in the object so that if it is not present, then there is no error and an alternate action can be taken.

This post will discuss different methods in which it can be checked if a key exists in an object.
Method 1: Using in operator
in operator checks for the presence of a property with the given key in an object and returns true if the property exists in the object and returns false if the property does not exist. Its syntax is

<property name> in object

Example,

let pen = {color: 'blue',
           getType() {
              return 'ink pen';
           }  
          };
if('color' in pen) {
   console.log('Key is present');
} else {
   console.log('Key is not present');
}

Above code when executed prints Key is present on the browser console since a property with name color is present in pen object.

in operator just checks for the presence of the supplied key in the object, it has no relation with the value of that key. Thus, if the value for a key is undefined in the object, it will still return true for that key.
Method 2: Using hasOwnProperty
hasOwnProperty function is invoked on an object and takes the name of the property in the form of a string as argument.
It returns true of the property is present and false if the property is not present. Example,

let pen = {color: 'blue',
           getType() {
              return 'ink pen';
           }  
          };
if(pen.hasOwnProperty('color')) {
   console.log('Key is present');
} else {
   console.log('Key is not present');
}

Above example prints Key is present since the object contains a property with the given key.

Method 3: Directly accessing property
An object’s property can be accessed by writing the object name followed by the name of property between single or double quotes and enclosing it within square brackets as shown below.

pen[‘color’]

If the property or key with this name exists in the object, then its value is returned while if the object does not contain a property with this key, then undefined is returned.
Thus, by comparing the returned value with undefined, it can be determined that the object contains the given key or not. Example,

let pen = {color: 'blue',
           getType() {
              return 'ink pen';
           }  
          };
if(pen['color'] === undefined) {
   console.log('Key is not present');
} else {
   console.log('Key is present');
}

Above code prints Key is present since the object has a property with name color.

To know about javascript objects in detail, refer this post.

Out of all the three methods, last method is the fastest and it should be used where ever possible.
If you liked this article, the hit the clap below.

Leave a Reply