JavaScript - get object length

3 points
Created by:

In this article, we would like to show you how to get object length in JavaScript.

Below examples show two ways how to do that:

  1. Using Object.keys() method,
  2. Using hasOwnProperty() method.

1. Object.keys() method example

In this solution we use:

  •  Object.keys() method which returns an array of the given object's own enumerable property names.
  • .length property to check the number of elements in that array.

Runnable example:

// ONLINE-RUNNER:browser;

var object = { 'a':1,'b':2,'c':3 }
console.log(Object.keys(object).length); // 3

2. hasOwnProperty() method example 

In this solution, we loop through the object properties checking whether the object has the specified property as its own with hasOwnProperty() method and we increase the counter for every existing property.

// ONLINE-RUNNER:browser;

var object = { 'a':1,'b':2,'c':3 }

var counter = 0;
for (var i in object) {
    if (object.hasOwnProperty(i)) {
console.log(counter); // 3


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂