object length javascript

Object Length in JavaScript

If you are working with JavaScript and need to find the number of properties in an object, you can use the Object.keys() method to get an array of the object's keys, and then use the length property of that array to get the number of keys:


    const myObj = { 
        name: "Raju", 
        age: 25, 
        location: "India" 
    };
    
    const numOfKeys = Object.keys(myObj).length;
    console.log(numOfKeys); // output: 3

The above code creates an object myObj with three properties - name, age, and location. The Object.keys(myObj) method returns an array of keys - ["name", "age", "location"], and the .length property of that array gives the number of keys, which is 3 in this case.

Another way to get the number of properties in an object is to loop through the object and count the number of properties:


    let count = 0;
    for(let prop in myObj) {
        if(myObj.hasOwnProperty(prop)) {
            count++;
        }
    }
    console.log(count); // output: 3

In the above code, we first initialize a variable count to 0. Then we loop through the properties of the object using a for...in loop. For each property, we check if the property belongs to the object itself (and not to its prototype) using the hasOwnProperty() method. If it does, we increment the count variable. Finally, we log the value of count, which gives us the number of properties in the object.

So, these are the two ways you can find the number of properties in an object in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe