How to check if a key exists in a JavaScript object

Given a JavaScript object, you can useinoperator.

Say you have onecarpurpose:

const car = {
  color: 'blue'
}

We can checkcolorThe attribute exists with this statement, resulting intrue:

'color' in car

We can use it under conditions:

if ('color' in car) {

}

Another way is to usehasOwnProperty()Object method:

car.hasOwnProperty('color')

When inheritance is an important part of the application structure, the difference isinWill result intrueEven the properties inherited by the parent object.hasOwnProperty()No. It will only returntrueIf the object directly has the attribute-not one of its ancestors.

When I need an attribute, I can use the fallback mechanism; if the attribute does not exist, fall back to the default value:

car.brand || 'Ford'

in casebrandThere is no attribute key on the object, the result of this statement isFordString.

Download mine for freeJavaScript beginner's manual


More js tutorials: