
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Key Exists in JavaScript Object
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
<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
<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