Arrays in JavaScript are standard objects with special handling of a class of property names called array indexes (names that are all digits in canonical integer form whose numeric value is >= 0 and < 2³²-1), special handling of the length property, and using Array.prototype (typically) as their prototype. Properties named by an array index name are called "elements." Other properties are just properties.
The length property of an array is always equal to the highest array element index the array contains plus one. In your first code block, there are no array elements (just non-element properties), so the length is 0. In your second, the highest array element index is 77, so length is 78.
If you're going to use non-array-element properties as in your first code block, it's generally best to use a non-array object ({}), not an array [].
If you want to know how many properties an object has, you can use Object.keys (if you don't care about inherited or non-enumerable properties). That would be good enough to get you 2 for your initial code block:
const items_in_cart = {}; // I've made this a non-array object
items_in_cart['rr'] = 1;
items_in_cart['mm'] = 2;
console.log(Object.keys(items_in_cart).length); // 2
Or you can use Object.getOwnPropertyNames (for the string-named ones) and/or Object.getOwnPropertySymbols (for the Symbol-named ones), which also don't include inherited properties but do include non-enumerable ones. You can get a count of all inherited enumerable properties by using a for-in loop. To get a count of all properties (whether own or inherited, enumerable or non-enumerable), you have to write a loop using getOwnPropertyNames and/or getOwnPropertySymbols on the object, then using Object.getPrototypeOf to go to its prototype object, and so on until you reach the end of the prototype chain.
If you want to know how many elements a sparse array (like your second one) has, this is one of the very few places I might use reduce (probably by wrapping it in a function with a useful name like getSparseCount):
function getSparseCount(array) {
// `reduce` only visits existing elements, not holes in a sparse array
const count = theArray.reduce(c => c + 1, 0);
return count;
}
const items_in_cart = [];
items_in_cart[50] = 1;
items_in_cart[77] = 2;
console.log(getSparseCount(items_in_cart));
function getSparseCount(array) {
// `reduce` only visits existing elements, not holes in a sparse array
const count = array.reduce(c => c + 1, 0);
return count;
}
Arraysare not meant forkey-valuepairs. You are abusing arrays. Use objects instead.undefined, tryconsole.log(items_in_cart[75])... that's because they are not initialized with any value. Array being chain of elements, 77th index cannot be created without 76th even though it is empty, so your array length is 78 instead of 2