Check if a JavaScript object has a property

Before using an object’s property in JavaScript, we need to check if it exists first. Otherwise, error or warning will be thrown instead.

There are 2 ways to detect whether a specified property exists in a specific object.

Use in operator

in operator returns true if an object or its prototype chain contains the specified property.

let car = { brand: 'Honda', model: 'City', year: 2021 };
if('brand' in car){
	alert('yes');
}

if(!('price' in car)){
	alert('there is no price property.');
}

Use hasOwnProperty method

This object.hasOwnProperty() can be used to check an object’s own keys and will only return true if key is available on object directly.

let car = { brand: 'Honda', model: 'City', year: 2021 };
if(car.hasOwnProperty('brand')){
	alert('brand exists');
}

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close