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 };
  // false, unreachable code, but the key exists!

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

Solution 2: use hasOwnProperty

 const objectInstanse = { key: undefined };
  // true, the same with null value


© 2019 4codev

Created with love by Sil.