Checking if a key exists in a JavaScript object?

Checking if a key exists in a JavaScript object?
Checking if a key exists in a JavaScript object?

In JavaScript, you can check if a key exists in an object using the in operator or the hasOwnProperty() method.

Using the in operator:

if ('key' in myObject) {
    // the key exists in the object
}

You can use the in operator to check if the key is in the object or in the object’s prototype chain.

Using the hasOwnProperty() method:

if (myObject.hasOwnProperty('key')) {
    // the key exists in the object
}

The hasOwnProperty() method only checks if the key exists in the object itself, and not in its prototype chain.

You can also use the Object.prototype.hasOwnProperty.call(myObject, key), this will check if myObject has the key, despite if myObject has been shadowed or overridden

if (Object.prototype.hasOwnProperty.call(myObject, key)) {
    // the key exists in the object
}

Additionally, you can use the Object.keys(myObject) function to return an array of all the keys of the object and use array.prototype.includes() function to check if the key exists or not.

if (Object.keys(myObject).includes(key)) {
    // the key exists in the object
}

It’s also worth noting that, using the [] notation on an object also checks if a key exists in the object and will return undefined if the key does not exist.

if(myObject[key] !== undefined){
    // key exists
}

You can choose the method that works best for your use case. Keep in mind that checking for existence of key before accessing it is best practice to prevent errors in case of missing keys.

Leave a Reply