JavaScript checks if the object has key | Example code

  • by

Use JavaScript in operator to checks if the object has key. Use myObj.hasOwnProperty('key') to check an object’s own keys and will only return true if key is available on myObj directly:

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Note: The in operator matches all object keys, including those in the object’s prototype chain.

OR

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

JavaScript checks if the object has key

Simple example code checking name key in given object.

<!DOCTYPE html>
<html>
<body>

  <script>
    const item = { id: '101', name: 'Goggles', price: 1499 };

    if ('name' in item){
      console.log(item)
    }
  </script>

</body>
</html> 

Output:

JavaScript checks if the object has key

Another way is to use the hasOwnProperty() method of the object:

const item = { id: '101', name: 'Goggles', price: 1499 };
var res = item.hasOwnProperty('color')

console.log(res)

Output: false

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.