How to Check If an Object has Key in JavaScript

To check if an object has a specific key (property) in JavaScript, you can use the “in” operator, “hasOwnProperty()” method, or “comparing with undefined”.

Method 1: Using the “in” operator

The “in” operator checks if an object has a specific property, its own or inherited from its prototype chain.

Syntax

propertyName in object

Example

const obj = {
  key1: 'value1',
  key2: 'value2'
};

console.log('key1' in obj);
console.log('key3' in obj);

Output

true
false

Method 2: Using the hasOwnProperty() function

The hasOwnProperty() method is a member of the Object.prototype that is used to check if an object has a specific property as its own (not inherited from its prototype chain).

Syntax

object.hasOwnProperty(propertyName)

Example

const obj = {
  key1: 'value1',
  key2: 'value2'
};

console.log(obj.hasOwnProperty('key1'));
console.log(obj.hasOwnProperty('key3'));

Output

true
false

Remember that if you want to check only for the Object’s properties, not properties inherited from its prototype chain, you should use the “hasOwnProperty()” method.

Method 3: Comparing with undefined

If you try to access a property that doesn’t exist on an object, it will return undefined. Hence, comparing with undefined can also be used to check if a property exists on an object.

Example

let obj = { key1: "value1", key2: "value2" };

console.log(obj.key1 !== undefined);
console.log(obj.key3 !== undefined);

Output

true
false

However, there’s a caveat with the undefined comparison: if the key exists but its value is explicitly set to undefined, this method will incorrectly suggest that the key doesn’t exist.

Conclusion

To check the existence of a key, regardless of its value (even if it’s undefined), it’s better to use the “in operator”.

If you’re sure that none of the values in your object will be undefined, then comparing with undefined could work, but it’s generally less robust than the in operator.

Leave a Comment