Length of a JavaScript associative array?

In JavaScript, arrays don't truly support associative arrays (key-value pairs with string keys). When you assign string keys to an array, they become object properties, not array elements, so the length property returns 0. To get the count of properties, use Object.keys().

The Problem with Array.length

When you add string keys to an array, they don't count as array elements:

var details = new Array();
details["Name"] = "John";
details["Age"] = 21;
details["CountryName"] = "US";
details["SubjectName"] = "JavaScript";

console.log("Array length:", details.length);  // 0, not 4!
console.log("Type:", typeof details);
Array length: 0
Type: object

Getting the Count with Object.keys()

Use Object.keys() to count the string properties:

var details = new Array();
details["Name"] = "John";
details["Age"] = 21;
details["CountryName"] = "US";
details["SubjectName"] = "JavaScript";

console.log("Property count:", Object.keys(details).length);
console.log("Keys:", Object.keys(details));
Property count: 4
Keys: [ 'Name', 'Age', 'CountryName', 'SubjectName' ]

Better Approach: Use Objects Instead

For key-value pairs, use plain objects rather than arrays:

var details = {
    "Name": "John",
    "Age": 21,
    "CountryName": "US",
    "SubjectName": "JavaScript"
};

console.log("Object keys count:", Object.keys(details).length);
console.log("Values:", Object.values(details));
Object keys count: 4
Values: [ 'John', 21, 'US', 'JavaScript' ]

Comparison

Method For Arrays For Objects Best Use
array.length Numeric indices only Not applicable True arrays with numeric indices
Object.keys().length String properties only All enumerable properties Key-value pairs (associative arrays)

Conclusion

For associative arrays in JavaScript, use Object.keys().length to count properties. Consider using plain objects instead of arrays for key-value data structures.

Updated on: 2026-03-15T23:18:59+05:30

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements