How to Get the Length of an Object in JavaScript

← PrevNext →

Everything in JavaScript is an Object. You can define a string object, an array object or you can simply use the Object constructor in JavaScript to create an object and add properties and values to it. Sometimes, you would also require knowing the length of an Object. One of simplest and perhaps the quickest way to get the length of a given object in JavaScript is by using the length property of Object.keys() method.

The Object.keys() method returns an array of object properties. For example, I have an array with few properties in it.

    var birds = {
        Name: 'Bald Eagle',
        Type: 'Hawk',
        ScientificName: 'Haliaeetus Leucocephalus'

Try it

The Output in your browser’s console would look like this.

Object Length in JavaScipt

👉 Remove duplicates in a JavaScript array using ES6 Set and from() function
Remove duplicates in JavaScript Array

It shows you all the properties with its keys (0, 1, …) and names. The above image also shows the length of the object (that is 3) at the end.

In your script you can add the length property to the Object.keys() method to get the length of the defined object.


Get the Length of a String Object

You can use the above method on a variety of objects. Now let’s apply this method to a String object.

    var student = new String('Arun Banik');

A String Object is created using the new operator. Like the array object above, I am using the length property of Object.keys() method to get the length of the string object. The output or the result would be 10.

Try it

Note: Alternatively, you can use student.length and this too will return 10. Learn more about how to find the length of a String using JavaScript

Getting the Length using Object Constructor

Object constructors in JavaScript are special functions to create objects. For example, I have defined a constructor and referred it as birds with some properties like name, type etc.

var bird = new Object()         // its an object constructor.
bird.name = 'Eurasian Collared-Dove';
bird.type = 'Dove';

To get the length of the object, I’ll again use Object.key().length.


The output would be 2, since I have defined two properties to the object. Add few more properties to the object and get the length.

← PreviousNext →