How to check if an object has a key in JavaScript?

Which of the following is the correct way to check if an object has a key?

if (myObj['key'] == undefined)

or

if (myObj['key'] == null)

or

if (myObj['key'])

What’s the best way to check if a JavaScript object has key and handle these scenarios?

The most reliable and explicit way to check if an object has a specific key is by using hasOwnProperty(). This method checks if the key exists directly on the object (not inherited from its prototype chain).

if (myObj.hasOwnProperty('key')) {
  console.log('Key exists');
} else {
  console.log('Key does not exist');
}

This method ensures you’re checking only the properties that belong directly to the object and not those inherited from its prototype chain.

If you want to check if a key exists on the object or anywhere in its prototype chain, the in operator is a great alternative. It will return true even if the key is inherited.

The in operator checks both the object’s own properties and those it inherits from its prototype chain. Use this if you don’t mind inherited keys.

This approach checks the value directly by accessing the property. However, it’s important to remember that undefined and null values are valid values for keys, so you’ll need to be careful.

Example 1: undefined Check

if (myObj['key'] === undefined) {
  console.log('Key does not exist');
} else {
  console.log('Key exists');
}

Example 2: null Check

if (myObj['key'] === null) {
  console.log('Key is null');
} else if (myObj['key'] === undefined) {
  console.log('Key does not exist');
} else {
  console.log('Key exists');
}

Example 3: General Falsy Check (Not Recommended)
if (!myObj['key']) {
  console.log('Key is either missing, null, undefined, or falsy');
} else {
  console.log('Key exists');
}

Important: Be aware with the falsy check (if (!myObj[‘key’])), as it will return true for values like null, undefined, false, 0, “”, and NaN. Use it only if you’re okay with those falsy values being treated as “non-existent.”