How to Get the Length of an Object in JavaScript

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'


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

Object Length in JavaScipt

It shows you all the properties with its keys (0, 1, …) and names. The 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.

Note: Alternatively, you can also use student.length and this too will return 10.

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() = '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 →

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: