How to Check if Key is Present in Object Javascript

 

In this tutorial, you will learn how to check if a key is present in object javascript.  It is extremely important to verify if a javascript object is missing any property before we start using it blindly.  Accessing any object property without performing any checks can lead to unexpected errors in production.

There are numerous ways to verify if a certain key exists in an object, but we are going to use the hasOwnProperty() method which I think is simple and easy to use.

In the following example, we have one global object.  We simply want to verify if this object has a name property or not.  After verification, we will display a Boolean value on the screen.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Check</button>
        <h1>Result</h1>
    </div>
    
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div{
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected two elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have a global variable obj and it holds an object as its value.
  • We have attached the click event listener to the button element.
  • In the click event handler function, we are using the hasOwnProperty() method to check if there is a property with a key name.
  • We are setting the inner text of the h1 element to the Boolean value returned by the hasOwnProperty() method.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let obj = {name:'Marks', age: 27};

btnCheck.addEventListener('click', () => {
    result.innerText = obj.hasOwnProperty('name') ?  'True' : 'False';
});