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'); }