Anjan Dutta

Check if key exists in object javascript

Check if key exists in object javascript

Updated On: 19/09/2021

The best way to check if a key exists in javascript object is to use the hasOwnProperty() method.

let person = {name: 'John', age: 30, address: '18/1, Dover lane' };
console.log(person.hasOwnProperty('address'));

This property returns true or false based upon the presence of that property.

Another way is to directly check the property by trying to access it.

See the below example:

let person = {name: 'John', age: 30, address: '18/1, Dover lane' };
if (person.address) {
.......
// Your logic goes here
.......
}

Or like this:

if (person['address']) {
.......
// Your logic goes here
.......
}

The only drawback of the latter method is that we can’t be sure if the object property doesn’t exist or its value is set to null or undefined or false.

Thanks for reading.