How to check if a JavaScript object property is undefined

By

Learn the correct way to check if a JavaScript object property is undefined using the typeof operator, which returns the string undefined for missing values.

~~~

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator.

typeof returns a string that tells the type of the operand. It is used without parentheses, passing it any value you want to check:

const list = []
const count = 2

typeof list //"object"
typeof count //"number"
typeof "test" //"string"

typeof color //"undefined"

If the value is not defined, typeof returns the ‘undefined’ string.

Now suppose you have a car object, with just one property:

const car = {
  model: 'Fiesta'
}

This is how you check if the color property is defined on this object:

if (typeof car.color === 'undefined') {
  // color is undefined
}

Why not just compare with undefined?

You could also write the check like this:

if (car.color === undefined) {
  // color is undefined
}

For object properties, both work the same way. The reason I prefer typeof is that it also works on variables that were never declared at all.

Comparing an undeclared variable with undefined throws a ReferenceError. typeof doesn’t:

typeof brand //"undefined", no error
brand === undefined //ReferenceError: brand is not defined

That makes typeof the safer habit.

Missing property or property set to undefined?

Here’s the edge case that trips people up. A property can exist on the object and hold the value undefined:

const car = {
  model: 'Fiesta',
  color: undefined
}

typeof car.color //"undefined"
typeof car.price //"undefined"

typeof can’t tell those two cases apart. Both return the same string, but color is there and price is not.

If you need to know whether the property exists at all, use the in operator:

'color' in car //true
'price' in car //false

in also finds properties inherited from the prototype chain. If you only want the object’s own properties, use Object.hasOwn():

Object.hasOwn(car, 'color') //true
Object.hasOwn(car, 'toString') //false
'toString' in car //true

Watch out for nested properties

One realistic pitfall: checking a property on something that’s itself undefined.

const car = {
  model: 'Fiesta'
}

typeof car.engine.type //TypeError: Cannot read properties of undefined

car.engine is undefined, so trying to read .type on it throws. typeof doesn’t save you here, because the error happens while evaluating the expression.

The fix is optional chaining:

typeof car.engine?.type //"undefined", no error

The ?. operator stops the evaluation as soon as it hits a nullish value, so the whole expression returns undefined instead of throwing.

~~~

Related posts about js: