How to check if a particular key exists in a JavaScript object?

In the some cases, we have to check a particular key already exist or not that we don't master about its value because its value maybe is undefined or null.

Consider the following case:
 const objectInstanse = { key: undefined };
 if(objectInstanse['key']){
  // false, unreachable code, but the key exists!
 }
Copy this code


Solution 1:

You should instead use the in operator like this:
 const objectInstanse = { key: undefined };
 if('key' in objectInstanse){
  // true, it's the same with null value
 }
Copy this code


Solution 2: use hasOwnProperty

 const objectInstanse = { key: undefined };
 if(objectInstanse.hasOwnProperty('key')){
  // true, the same with null value
 }
Copy this code


© 2019 4codev

Created with love by Sil.