How to use the “in” operator In Javascript
The “in” operator checks if a property exists in an object or its prototype chain.
Syntax:
if ('propertyName' in objectName) {
// Code to execute if property exists
}
Here, “propertyName” is the name of the property you want to check, and “objectName” is the name of the object you want to check.
Example: This example shows the use of in operator.
Javascript
const person = { name: 'John' , age: 30, address: { city: 'New York' , state: 'NY' } }; if ( 'age' in person) { console.log( 'Person object has the age property' ); } if ( 'email' in person) { console.log( 'Person object has the email property' ); } else { console.log( 'Person object does not have the email property' ); } |
Person object has the age property Person object does not have the email property
How to Check if an Object has a Specific Property in JavaScript ?
In JavaScript, objects can have properties that store data or functions. Sometimes it is necessary to check whether an object has a specific property. This can be useful, for example, when you want to avoid calling a function on an object that doesn’t have that function defined as a property. In this article, we will be discussing different approaches to check whether an object has a specific property or not.
These are the following approaches:
Table of Content
- Using the “in” operator
- Using hasOwnProperty() method
- Using the “typeof” Operator