How to Check If an Object has Key in JavaScript

To check if an object has a specific key (property) in JavaScript, 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.

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

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.

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.