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:
'key' in obj // true, if the property exists (even if it's undefined)
Object.hasOwn(obj, 'key') // the same thing, just saferBut '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:
const obj = {
a: undefined
};Now compare it with an object without the property:
const obj2 = {};3. The difference in practice
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:
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
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, undefinedOnly 'a' in data returns true,
meaning the key exists, even if its value is undefined.
Summary
| Check | What it does | Distinguishes key existence? |
|---|---|---|
obj.key === undefined | Checks only the value | No |
'key' in obj | Checks whether the key exists | Yes |
'key' in obj && obj.key === undefined | Checks both conditions | Yes |
Object.hasOwn(obj, 'key') | Modern equivalent of in | Yes |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.