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.
Approaches:
Using the “in” operator: 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.
For example:
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
Using hasOwnProperty() method: The hasOwnProperty() method checks if an object has a property of its own and is not inherited from its prototype chain.
Syntax:
if (objectName.hasOwnProperty('propertyName')) { // 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:
Javascript
const person = { name: 'John' , age: 30, address: { city: 'New York' , state: 'NY' } }; if (person.hasOwnProperty( 'age' )) { console.log( 'Person object has the age property' ); } if (person.hasOwnProperty( 'email' )) { 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
Using the “typeof” Operator: You can also use the “typeof” operator to check if an object has a specific property.
Syntax:
if (typeof object.property !== 'undefined') { // Property exists in object } else { // Property does not exist in object }
Here, “property” is the name of the property that you want to check for, and “object” is the object that you want to check. The “typeof” operator returns the type of the value of the specified property, so if the property does not exist in the object, it will return “undefined”.
Example:
Javascript
const myVar = "Hello World" ; console.log( typeof myVar); // Output: string |
In this example, we’re using the “typeof” operator to determine the type of the “myVar” variable, which is a string. You can use the “typeof” operator to check for different types of values, such as “number”, “boolean”, “undefined”, “object”, “function”, and “symbol”.