Check if an object has a key in JavaScript
Intermediate · 4 min read
"Does this object have a fare?" sounds like one question. In JavaScript it is really three: is there a key called fare, is its value something other than undefined, and is its value "truthy"? They give different answers more often than you would think, and picking the wrong one causes quiet bugs, like a free staff shuttle being treated as if it had no fare at all.
In this tutorial you will compare three ways of checking: the in operator, Object.hasOwn, and !== undefined. You will test them against a key whose value is undefined, a key the object inherited, and a fare of zero. You need to know what an object is and what true and false are.
Keys and values are different things
An object can have a key whose value is undefined:
const trip = { route: 'Yaba - Ikeja', fare: 200_00, driver: undefined };
The driver key exists. It was written. It just holds nothing yet, maybe because no driver has been assigned. So "is there a key?" and "is there a value?" can have different answers.
Truthy and falsy
When JavaScript uses a value as a condition, as in if (x), it treats a few values as false: 0, '' (empty text), false, null, undefined and NaN. These are called falsy. Everything else is truthy. That's convenient, but a fare of 0 is a real fare, and if (fare) treats it as missing.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
84 Does the key exist, or is the value just missing?
fairDecide whether an object has a property. Compare in, Object.hasOwn and a plain !== undefined against a key whose value is undefined, an inherited key, and a fare of zero.
Stuck? Three hints, smallest first
- 1.
'key' in objasks about the key, not the value. - 2.
inalso finds inherited properties.Object.hasOwndoes not. - 3. A zero fare is falsy, so
if (obj.fare)is asking the wrong question.
Step 1: ask about the key with in
'key' in obj answers true if the object has that key, whatever its value:
const trip = { route: 'Yaba - Ikeja', fare: 200_00, driver: undefined };
console.log('route' in trip); // true
console.log('driver' in trip); // true
console.log(trip.driver); // undefined
driver is in the trip even though reading it gives undefined. The in operator asks about the key, not the value. (The fare is in kobo: 200_00 is 20,000 kobo, ₦200.)
Step 2: the !== undefined test disagrees
A very common check is "is the value not undefined?":
const trip = { route: 'Yaba - Ikeja', fare: 200_00, driver: undefined };
console.log(trip.driver !== undefined); // false
console.log(trip.color !== undefined); // false
Both lines say false, but the situations are different: driver exists and holds undefined, while color was never written. This test can't tell them apart. Sometimes that's fine, because you only care whether there is a usable value. When you need to know whether the key is there, use in or Object.hasOwn.
Step 3: in also finds inherited keys
Every object quietly inherits some built-in properties, such as toString. You never wrote them, but in finds them:
const trip = { route: 'Yaba - Ikeja', fare: 200_00, driver: undefined };
console.log('toString' in trip); // true
console.log(Object.hasOwn(trip, 'toString')); // false
console.log(Object.hasOwn(trip, 'driver')); // true
Object.hasOwn(obj, key) only counts the object's own keys, the ones written on it. It still finds driver, because that key was written, even with undefined in it.
This matters when the key comes from outside, for example from a form or a web address. If someone types toString, a check with in says "yes, that exists", and your code goes on to use a built-in function as if it were data.
Step 4: a fare of zero
Now the staff shuttle, which is free:
const staffShuttle = { route: 'staff shuttle', fare: 0 };
if (staffShuttle.fare) {
console.log('has a fare');
} else {
console.log('no fare?'); // no fare?
}
console.log(Object.hasOwn(staffShuttle, 'fare')); // true
0 is falsy, so the if goes the wrong way. The key is plainly there and its value is a real number. if (obj.fare) asks "is the fare truthy?", which is not the question you meant.
Step 5: keep the zero with ??
If you want a default only when the fare is genuinely missing, use ??, which only replaces null and undefined:
const staffShuttle = { route: 'staff shuttle', fare: 0 };
console.log(staffShuttle.fare ?? 500_00); // 0
console.log(staffShuttle.fare || 500_00); // 50000
|| replaces anything falsy, so the free shuttle suddenly costs ₦500. ?? keeps the zero.
The full solution
The answer panel checks the trip with in, !== undefined and Object.hasOwn, tries an inherited key, and tests the zero fare with truthiness and with ??. Press Run to see the output.
const trip = {
route: 'Yaba - Ikeja',
fare: 200_00,
driver: undefined, // the key exists; the value does not
};
const staffShuttle = { route: 'staff shuttle', fare: 0 };
console.log('driver in trip:', 'driver' in trip, '| value:', trip.driver);
console.log('toString in trip:', 'toString' in trip, '| own:', Object.hasOwn(trip, 'toString'));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('in finds a key', 'route' in trip, true);
test('a key holding undefined still exists', 'driver' in trip, true);
test('so the !== undefined test disagrees with it', trip.driver !== undefined, false);
test('in also finds inherited keys', 'toString' in trip, true);
test('Object.hasOwn refuses those', Object.hasOwn(trip, 'toString'), false);
test('but does find the key holding undefined', Object.hasOwn(trip, 'driver'), true);
test('a zero fare is falsy, so truthiness asks the wrong question', Boolean(staffShuttle.fare), false);
test('the key is plainly there', Object.hasOwn(staffShuttle, 'fare'), true);
test('and ?? keeps the zero where || would replace it', staffShuttle.fare ?? 500_00, 0);
Three questions get confused with each other. "Is there a key?" is in or Object.hasOwn. "Is the value something?" is !== undefined. "Is the value truthy?" is if (obj.fare) — and that last one is false for 0, '' and false, all of which are real values a fare, a note or a flag might legitimately hold.
'toString' in trip being true is why in is the wrong tool for checking user data: every object inherits a handful of properties, so a lookup keyed on an untrusted string can report a hit that was never written. Object.hasOwn(obj, key) is the modern one-liner for own properties; before it existed the incantation was Object.prototype.hasOwnProperty.call(obj, key), written that way because an object can have its own key called hasOwnProperty.
Common mistakes
- Using
if (obj.fare)to ask whether a fare exists. It is false for0,''andfalse, which are real values. - Using
inon keys from users. It also finds inherited keys such astoString. UseObject.hasOwn. - Treating
undefinedas "no key". A key can exist and holdundefined. OnlyinandObject.hasOwncan see the difference.
Try it yourself
- Write
hasFare(trip)that returnstruefor{ fare: 0 }andfalsefor{}. - Check
'constructor' in {}andObject.hasOwn({}, 'constructor'). Explain the two answers. - Write
describe(obj, key)that returns'missing','empty'(the key holdsundefined) or'set'.