How to check if a key exists in a JavaScript object?

To check if a key exists in a JavaScript object, use one of these methods:

1. in Operator

Checks if a key exists anywhere in the object or its prototype chain.

const obj = { a: 1, b: undefined };

// Check if 'a' exists
console.log('a' in obj);       // true
console.log('b' in obj);       // true (key exists, value is undefined)
console.log('c' in obj);       // false

2. Object.hasOwnProperty()

Checks if a key is a direct (own) property (excludes prototype chain).

console.log(obj.hasOwnProperty('a'));   // true
console.log(obj.hasOwnProperty('b'));   // true
console.log(obj.hasOwnProperty('c'));   // false

Safer Syntax (avoids issues if hasOwnProperty is overridden):

console.log(Object.prototype.hasOwnProperty.call(obj, 'a')); // true

3. Check for undefined Value

Caution: Only use if the key’s value cannot be undefined.

console.log(obj.a !== undefined);  // true (key exists)
console.log(obj.c !== undefined);  // false (key does not exist)

4. Object.keys() with includes()

Check if the key is in the object’s own enumerable properties:

console.log(Object.keys(obj).includes('a'));  // true
console.log(Object.keys(obj).includes('c'));  // false

5. Reflect.has() (ES6)

Same behavior as the in operator.

console.log(Reflect.has(obj, 'a'));  // true
console.log(Reflect.has(obj, 'c'));  // false

Key Considerations

MethodChecks Prototype Chain?Works for undefined Values?Notes
in✅ Yes✅ YesSafest for general use
hasOwnProperty❌ No✅ YesBest for own properties
obj.key !== undefined❌ No*❌ No (fails if value is undefined)Avoid unless certain of values
Object.keys().includes()❌ No✅ YesSlow for large objects
Reflect.has()✅ Yes✅ YesES6 alternative to in

Example Workflow

const user = { id: 1, name: 'Alex' };

// Safest check for own properties:
if (Object.hasOwnProperty.call(user, 'name')) {
  console.log('Name exists:', user.name);
}

// Check including prototype chain:
if ('toString' in user) {
  console.log('toString exists (inherited from prototype)');
}

Pitfalls to Avoid

  1. Using obj.key directly:
   if (obj.key) { ... } // ❌ Fails if value is falsy (0, "", null, etc.)
  1. Assuming hasOwnProperty is safe:
   const obj = { hasOwnProperty: 'overridden' };
   obj.hasOwnProperty('a'); // ❌ Throws error (not a function)

Recommendation:

  • Use in for general checks (including inherited keys).
  • Use Object.hasOwnProperty() for strict own-property checks.
  • Avoid undefined checks unless you control the object’s values.

Leave a Reply

Your email address will not be published. Required fields are marked *