How to Check if an Object Key Exists in JavaScript?

There are various methods in JavaScript that you can use to check whether a key exists in your object or not :

Using the hasOwnProperty method

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

if (myObject.hasOwnProperty('key1')) {
    console.log('Key exists!');
} else {
    console.log('Key does not exist!');
}

Using the in operator

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

if ('key1' in myObject) {
    console.log('Key exists!');
} else {
    console.log('Key does not exist!');
}

Using undefined check

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

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

Leave a Reply

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