Skip to main content

Missing property

In JavaScript, a property can be missing entirely, or it can exist but have the value undefined, and these are two different situations!

Let's break down how to tell them apart.


1. Checking whether a property exists

First, let's recall how to check whether a property is in the object:

javascript
'key' in obj // true, if the property exists (even if it's undefined) Object.hasOwn(obj, 'key') // the same thing, just safer

But 'key' in obj doesn't tell you what the property equals, it only checks that the key exists in the object.


2. Checking that a property exists but equals undefined

Example situation:

javascript
const obj = { a: undefined };

Now compare it with an object without the property:

javascript
const obj2 = {};

3. The difference in practice

javascript
console.log('a' in obj); // true (the property exists) console.log('a' in obj2); // false (the property does not exist) console.log(obj.a === undefined); // true console.log(obj2.a === undefined); // true (both return true!)

The problem: a simple check obj.a === undefined does not distinguish "the property is missing" from "the property exists, but is undefined".


4. The solution - combine the checks

To find out for sure that a property exists and equals undefined, you need:

javascript
if ('a' in obj && obj.a === undefined) { console.log('The property exists, but its value is undefined'); }

'a' in obj checks whether the key exists, while obj.a === undefined checks the value.


5. Example: comparing all the cases

javascript
const data = { a: undefined, b: 10 }; console.log('a' in data, data.a); // true, undefined console.log('b' in data, data.b); // true, 10 console.log('c' in data, data.c); // false, undefined

Only 'a' in data returns true, meaning the key exists, even if its value is undefined.


Summary

CheckWhat it doesDistinguishes key existence?
obj.key === undefinedChecks only the valueNo
'key' in objChecks whether the key existsYes
'key' in obj && obj.key === undefinedChecks both conditionsYes
Object.hasOwn(obj, 'key')Modern equivalent of inYes

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.