It should be 1.
No, it should be 667, because the way length defined for standard arrays in JavaScript that are not arrays at all . Arrays in JavaScript are inherently sparse, that is, they can have holes in them (indexes where no value is stored).
How can I get a good score in the fastest way?
The only way is a loop. For instance:
var count = 0; myArr.forEach(function() { ++count; }); console.log(count);
... or through reduce , as in maček answer . forEach , reduce and other similar only entries that actually exist, so they skip holes in sparse arrays.
I should mention that since IE8 still (sigh) has a fair market share, you need to color forEach and reduce and such on it if you want to use them. (This is easy.)
To do this without any shimming and only read the actual properties of the index (not other kinds of properties), then freely:
var count = 0, name; for (name in myArr) { if (myArr.hasOwnProperty(name) && /^[0-9]+$/.test(name)) { ++count; } }
This uses a slightly loose definition of what an index property name is; if you want reliable, see the "Use in-in correctly" section of this answer .
source share