How do you check whether a property exists on an object?
Use Object.hasOwn(obj, key) for own properties and the in operator to include inherited ones. Comparing to undefined is unreliable, because a property can exist and hold undefined.
Explain it simply
Checking obj.key !== undefined asks "is the value something?", which is not the same as "does the key exist?". A student record might have phone: undefined on purpose, and the key still exists.
Better tools:
key in obj: true if the key is on the object or its prototype chain.Object.hasOwn(obj, key): true only for the object's own keys. It is the modern replacement forobj.hasOwnProperty(key), which breaks on objects with no prototype.obj?.key: not a check at all, but a safe read that returns undefined instead of throwing.
Example
const o = { a: undefined, b: 0 };
console.log("a" in o); // Output: true
console.log(o.a !== undefined); // Output: false
console.log(Object.hasOwn(o, "a")); // Output: true
console.log(Object.hasOwn(o, "c")); // Output: false
console.log("toString" in o); // Output: true
console.log(Object.hasOwn(o, "toString")); // Output: falseWhat to say in the interview
"For own properties I use Object.hasOwn; for 'own or inherited' I use in. Checking against undefined is wrong when the property exists with an undefined value. For nested safe access I use optional chaining."
Common mistakes
- Using if (obj.key) to test existence. Values like 0 and empty string fail it.