Nate Rook Nate Rook - 1 month ago 4x
Javascript Question

How do I find out the number of elements in a Javascript array?

In the ECMAScript specification,

is not defined as the number of elements in an array.

The length property of an Array instance is a data property whose value is always numerically greater than the name of every configurable own property whose name is an array index.

That is, a Javascript engine could cause
to be positive infinity in all cases, and it would be compliant with the standard.

Taking this into account, how should I count the elements in an array?


That's not the only specification of the length property.

The specification of the abstract operation ArrayCreate(length, proto) says that the length property is initialized to the length parameter.

And the specification of Array Exotic Objects explains how it's updated:

Specifically, whenever an own property is added whose name is an array index, the value of the length property is changed, if necessary, to be one more than the numeric value of that array index

Other array manipulations are defined in terms of these operations, so the length property should accurately reflect the indexes of array elements.