How to check whether a key exist in JavaScript object or not?


There are a couple of ways to find whether a key exist in javascript object or not.

Let's say we have an 'employee' object as shown below.

   var employee = {
      name: "Ranjan",
      age: 25
   }

Now we need to check whether 'name' property exist in employee object or not.

1) 'In' operator

We can use 'in' operator on object to check its properties. The 'in' operator also looks about inherited property if it does not find any actual properties of the object.

In the following example when 'toString' is checked whether present or not, the 'in' operator scrutinizes through the properties of the object. Once it confirmed its absence, it comes to the base properties of the object. Since, 'toString' is a base property it displays 'true' as shown in the output.

Example

Live Demo

<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write("name" in employee);
   document.write("</br>");
   document.write("salary" in employee);
   document.write("</br>");
   document.write("toString" in employee);
</script>
</body>
</html>

output

true
false
true


2) hasOwnProperty() 

This method scrutinizes through the object only for actual properties but not for any kind of inherited properties. If there are actual properties, this method displays either true or false based on their availability.

In the following example we also searched for inherited properties such as 'toString' so it displays false as shown in the output.

Example

Live Demo

<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write(employee.hasOwnProperty('toString'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('name'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('salary'));
</script>
</body>
</html>

Output

false
true
false

Updated on: 30-Jul-2019

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements