Associative arrays are regular arrays in JavaScript where an element is present at a specific index. Associative arrays, on the other hand, are essentially JavaScript objects with user-defined keys in place of the index. Basically, we can say that it stores Key-Value pairs.


let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}

Key1, Key2, and Key3 are its indexes, and Value1, Value2, and Value3 are its elements. Arr is an associative array in this case.

let arr = {"apple": 10, "grapes": 20};

Method 1

The object contains keys method can be used to determine the object's length.

Object.keys(counterArray).length; // Output 3

Method 2

We can also count the object's own properties while iterating across the object to determine its length. By doing this, we will disregard the following characteristics of the object's prototype chain:

function getLength(object) {
  var count = 0;
  for(key in object) {
    // hasOwnProperty method check own property of object
    if(object.hasOwnProperty(key)) count++;
  return count;

Method 3

The getOwnPropertyNames method is supported by all current browsers (including IE9+), hence the following code can be used to determine the length:

Object.getOwnPropertyNames(counterArray).length; // Output 3

Method 4

The method size in the Underscore and Lodash libraries is specifically designed to determine the object length. Although using one of these libraries only for the size technique is not something we advise, if it is currently being done in your project, why not?

_.size({one: 1, two: 2, three: 3});
=> 3

Recommended Posts

View All

Difference between var and let in JavaScript

Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

JavaScript Program to Create Objects in Different Ways

Learn different ways to create objects using JavaScript with our step-by-step guide. From object literals to constructor functions and classes, this p...

What is the Temporal Dead Zone in JavaScript?

The time frame in which access to the let and const declarations is prohibited is known as the Temporal Dead Zone.

Understanding Hoisting in JavaScript

Learn about hoisting in JavaScript: how variables and functions are moved to the top of their scope during compilation, affecting code behavior.

Top 10 ES6 Features Every JavaScript Developer Must Know

The specification for JavaScript implementation is provided by ES6. Learn about its recently added ES6 features that make writing JavaScript easier!