3

Array(3) yields [ , , ], which has a length of 3.

[1, 2, 3].forEach loops 3 times, as expected.

Neither Array(3).forEach nor [ , , ].forEach loops at all, however.

Why is this? I thought I'd discovered a way of doing something n times without using for loops, and am disappointed to find it doesn't work!

RobertAKARobin
  • 3,933
  • 3
  • 24
  • 46
  • 3
    It's a sparse array. The unspecified elements are not actually there. For instance, try iterating over [1,,]. It will loop for the value 1, but not for the two unspecified values. Or try [1,,3]. It will loop twice with values 1 and 3. – RJM Apr 01 '16 at 03:49
  • FYI, you can convert from sparse to non-sparse, using `.apply`: `Array.apply(undefined, Array(3)).forEach(...)` works fine, creating an `Array` of size three with initialized values (of `undefined`, because why not? :-) ) that loops three times as expected. – ShadowRanger Apr 01 '16 at 03:56
  • You should be looking at [*ECMAScript 2015 Iterator protocols*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). *apply* converts the supplied array to a parameter list and uses a different algorithm to *forEach*. – RobG Apr 01 '16 at 04:00

1 Answers1

2

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays)

Example from MDN:

Fiddle

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Have a look at MDN article.

.

Khalid Hussain
  • 1,675
  • 17
  • 25