Sub topic 6
Checking Whether a Property Exists
This chapter assumes you can create objects with literals, read properties with dot and bracket notation, and add or delete properties. You should also be comfortable running small snippets in Node.js or a browser console.
Asking "does this object have a property called x?" sounds simple. JavaScript gives you several ways to ask it, and each one answers a slightly different question. Choosing the wrong one causes some of the most common object bugs: a valid 0 treated as missing, an inherited method mistaken for data, or a TypeError thrown three levels deep in a response object.
Why reading a property is not enough
Reading a property that doesn't exist does not throw. It returns undefined:
const settings = { volume: 0, theme: undefined };
console.log(settings.volume); // 0
console.log(settings.theme); // undefined
console.log(settings.language); // undefinedThis creates two problems.
The first problem is that theme and language look the same when you read them. One property exists and holds undefined. The other does not exist at all. A plain read cannot tell them apart.
The second problem is that truthiness checks lie. A common shortcut is if (settings.volume), but 0, "", false, and NaN are all falsy. A volume of 0 is a real value, and that check treats it as missing.
const settings = { volume: 0 };
if (settings.volume) {
console.log("volume is set");
} else {
console.log("volume is missing"); // printed, which is wrong
}Comparing with undefined (settings.volume !== undefined) fixes the falsy-value problem. It still cannot separate "missing" from "present but undefined". For that you need an operator that checks for the key itself.
The `in` operator
key in object returns true if the object has a property with that key, whatever its value is:
const settings = { volume: 0, theme: undefined };
console.log("volume" in settings); // true
console.log("theme" in settings); // true
console.log("language" in settings); // falseThe left side is a property key. Strings, numbers (converted to strings), and symbols all work:
const id = Symbol("id");
const record = { [id]: 42, 3: "three" };
console.log(id in record); // true
console.log(3 in record); // true
console.log("3" in record); // true`in` also sees inherited properties
in does not stop at the object's own properties. It also checks every object the object inherits from. The prototype chain gets its own chapter later. For now, the key point is that most objects inherit methods from Object.prototype:
const empty = {};
console.log("toString" in empty); // true
console.log("hasOwnProperty" in empty); // trueempty has no properties of its own, but in reports true because toString is inherited. This matters when you use objects as lookup tables keyed by user input:
const allowedCommands = { start: true, stop: true };
function isAllowed(cmd) {
return cmd in allowedCommands;
}
console.log(isAllowed("start")); // true
console.log(isAllowed("constructor")); // true, which is a bug`in` requires an object on the right
Using in with a primitive on the right side throws:
try {
console.log("length" in "hello");
} catch (err) {
console.log(err instanceof TypeError); // true
}If the value might be a primitive, null, or undefined, guard it first, for example with typeof value === "object" && value !== null.
Own properties: `Object.hasOwn`
An own property is a property defined directly on the object, as opposed to one inherited from its prototype. Object.hasOwn(obj, key) returns true only for own properties:
const allowedCommands = { start: true, stop: true };
console.log(Object.hasOwn(allowedCommands, "start")); // true
console.log(Object.hasOwn(allowedCommands, "constructor")); // false
console.log(Object.hasOwn(allowedCommands, "toString")); // falseLike in, it counts a property that holds undefined:
const settings = { theme: undefined };
console.log(Object.hasOwn(settings, "theme")); // trueThe spine example shows the difference between in and Object.hasOwn side by side, and how delete changes the answer:
const proto = { inherited: true };
const obj = Object.create(proto);
obj.own = undefined;
console.log("own" in obj); // true
console.log("inherited" in obj); // true
console.log(Object.hasOwn(obj, "inherited")); // false
console.log(obj.missing?.deep); // undefined
delete obj.own;
console.log("own" in obj); // falseObject.create(proto) makes a new object whose prototype is proto, so inherited is visible through in but is not an own property. After delete obj.own, the key is gone entirely. Assigning obj.own = undefined would not have had the same effect.
Why not `obj.hasOwnProperty(key)`?
Older code uses obj.hasOwnProperty(key). That is a method inherited from Object.prototype, and it breaks in two situations:
// 1. Objects with no prototype do not inherit the method
const dict = Object.create(null);
dict.apple = 1;
console.log(typeof dict.hasOwnProperty); // "undefined"
// dict.hasOwnProperty("apple") would throw a TypeError
// 2. An own property can shadow the method
const tricky = { hasOwnProperty: () => true };
console.log(tricky.hasOwnProperty("anything")); // true, which is wrong
// Object.hasOwn works in both cases
console.log(Object.hasOwn(dict, "apple")); // true
console.log(Object.hasOwn(tricky, "anything")); // falseThe old workaround was Object.prototype.hasOwnProperty.call(obj, key). Object.hasOwn (ES2022, available in all current browsers and Node.js 16.9+) does the same thing with less noise. Use it in new code.
Choosing a check
| Check | Inherited counts? | Key with value `undefined` | Falsy values like `0` | Throws on `null` target |
|---|---|---|---|---|
| `if (obj.key)` | Yes | Reported missing | Reported missing | Yes |
| `obj.key !== undefined` | Yes | Reported missing | Reported present | Yes |
| `"key" in obj` | Yes | Reported present | Reported present | Yes |
| `Object.hasOwn(obj, "key")` | No | Reported present | Reported present | Yes |
Every check throws when the target itself is null or undefined. That is the problem optional chaining solves.
Optional chaining for nested access
Nested data often has optional branches. Reading a property of undefined throws:
const order = { id: 1, customer: null };
try {
console.log(order.customer.address.city);
} catch (err) {
console.log(err.message); // "Cannot read properties of null (reading 'address')"
}The exact message varies by engine. Optional chaining (?.) stops evaluation and returns undefined when the value on its left is null or undefined:
const order = { id: 1, customer: null };
console.log(order.customer?.address?.city); // undefined
console.log(order.customer?.["address"]); // undefinedIt has three forms:
const api = {
user: { tags: ["admin"] },
log(msg) { return "logged: " + msg; }
};
console.log(api.user?.name); // property: undefined
console.log(api.user?.tags?.[0]); // bracket/index: "admin"
console.log(api.log?.("hi")); // call: "logged: hi"
console.log(api.notify?.("hi")); // call on a missing method: undefinedShort-circuiting covers the whole chain
When ?. finds null or undefined, it skips the entire rest of the chain, including later plain dots:
const data = { a: null };
console.log(data.a?.b.c.d); // undefined, no errorYou don't need ?. at every step, only where a value may be missing. Placing ?. everywhere hides real bugs. If customer must always exist, write order.customer.address?.city. A missing customer should then throw loudly.
Combining with `??`
Optional chaining produces undefined. The nullish coalescing operator ?? supplies a fallback only for null or undefined, so a falsy value like 0 survives:
const prefs = { display: { fontSize: 0 } };
console.log(prefs.display?.fontSize ?? 16); // 0
console.log(prefs.display?.fontSize || 16); // 16, which is probably wrong
console.log(prefs.audio?.volume ?? 50); // 50What optional chaining does not do
To check existence safely when the object itself might be missing, combine the two ideas:
function hasOwnSafe(obj, key) {
return obj != null && Object.hasOwn(Object(obj), key);
}
console.log(hasOwnSafe(null, "x")); // false
console.log(hasOwnSafe({ x: 1 }, "x")); // true
console.log(hasOwnSafe("hi", "length")); // trueobj != null is true for everything except null and undefined. Wrapping with Object(obj) is optional here, because Object.hasOwn already converts primitives, but it makes the intent clear.
Edge cases worth knowing
- Arrays:
inandObject.hasOwncheck indices as keys. Inconst a = [1, , 3],1 in aisfalsebecause index 1 is a hole, whilea[1]isundefinedeither way. - Getters:
inandObject.hasOwndo not run getters. Readingobj.keydoes. Existence checks therefore have no side effects. - Non-enumerable properties:
Object.hasOwn([], "length")istrueeven thoughlengthdoes not appear inObject.keys([]). Existence and enumerability are separate questions. A later chapter covers enumerability. deletevs.undefined: onlydeleteremoves the key. Setting a property toundefinedleaves it present forinandObject.hasOwn.
Exercise
Given const o = Object.create({ shared: 1 }); o.local = undefined; o.count = 0;, what do these print: "shared" in o, Object.hasOwn(o, "shared"), "local" in o, o.local !== undefined, Boolean(o.count), Object.hasOwn(o, "count")?
Show answer
true, false, true, false, false, true. shared is inherited, so in sees it and Object.hasOwn does not. local exists but holds undefined, so in says present while the undefined comparison says missing. count is an own property whose value 0 is falsy.
Exercise
A function getCity(order) must return the customer's city, or "Unknown" when order, order.customer, or order.customer.address is null or undefined. An empty string city should be returned as is. Write it in one expression.
Show answer
const getCity = (order) => order?.customer?.address?.city ?? "Unknown"; Optional chaining stops at the first null or undefined link, and ?? (not ||) keeps an empty string because "" is neither null nor undefined.
Exercise
Why can isAllowed("constructor") return true for const allowed = { start: true } with cmd in allowed, and what are two ways to fix it?
Show answer
in checks inherited properties, and constructor is inherited from Object.prototype. Fix it with Object.hasOwn(allowed, cmd), or build the table with Object.create(null) (or use a Map or Set) so that no keys are inherited.