Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you check whether a property exists on an object?

SHORT ANSWER

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 for obj.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

js
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: false

What 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.

#javascript#objects

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.