What are Objects in Javascript?
Objects are associated with real-life objects. It is a collection of properties with a key-value pair and methods. Methods are inherited from Objects. prototype and can be overwritten and new methods can be defined as well.
A real-world example of an object would be a phone with properties such as processor, RAM, camera, battery life, etc. All objects have the same properties but the property value will differ for RAM it could be 2GB,4GB,8GB, etc.
Javascript Object inherently doesn’t have any length property or in-built method. Therefore we’ll explore a few ways how to evaluate the object length. A few methods to achieve the length are as follows:
- for… in loop
- Object.keys()
- Object.entries()
- for..in and Object.hasOwnProperty()
- Lodash_.size()
Method 1: Using for…in the loop
The most naive way is to declare a counter and increment it while looping over the object properties.
const myObject = { a:0, b:1, c:2, d:3 }; //Initialize a count variable to 0 let count = 0; //Loop through each property of the object for (const key in myObject) { count++; } console.log("Length of the object:", count);

Method 2: Using Object.keys()
The Object.keys() returns an array containing the property key of the object. Since it returns an array we can find the length of the return array.
const myObject = { a:0, b:1, c:2, d:3 }; const length = Object.keys(myObject).length; console.log(length);

Method 3: Object.entries() static method
Object.entries() method acts the same as Object.keys() method. Similarly, it also returns an array of enumerable property of the object.
const myObject = { a:0, b:1, c:2, d:3 }; const length = Object.entries(myObject).length; console.log(length);

Method 4: for..in and Object.hasOwnProperty()
hasOwnProperty() method returns a boolean value true if the object contains the property passed in the method else returns false. This method along with for..in loop updates the counter to count the number of properties hence giving length.
const myObject = { a:0, b:1, c:2, d:3 }; let count = 0; for (const key in myObject) { if (myObject.hasOwnProperty(key)) { count++; } } console.log(count);

Method 5: Lodash_.size() method from Lodash library
_size() method provides the size of array or object which is part of lodash javascript library
const myObject = { a:0, b:1, c:2, d:3 }; const _ = require("lodash"); let CP = _.size(myObject); console.log(CP);

Conclusion:
- From the above methods the most optimized way and preferred way to find the length of an object is using for..in the loop or for…in along with hasOwnProperty()