Javascript programming articles and tutorials for beginner | Anjan Dutta

Check if key exists in object javascript

Check if key exists in object javascript

The best way to check if 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.

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

How to determine the length of objects in JavaScript?

The optimal way of determining an object’s length in Javascript is to use the Object.keys() method. This method returns an array containing all enumerable properties of an object. Then we will use length property to get the length of that array and it will return the correct length.

See below example:

let person = {name: 'John', age: 30, address: '18/1, Dover lane' };
var size = Object.keys(person).length;
Edit this page on GitHub