5

In the following code, I'm not sure what [] is supposed to represent. I'm assuming it just symbolizes the most recently declared array. Can anyone clarify?

var lists = [racersList, volunteersList];
[].forEach.call(lists, function(list) {
    ...
});
earllee
  • 285
  • 3
  • 11

1 Answers1

17

It's an empty array. It really doesn't matter what array it is; it just needs some array to get an array's forEach method. You could also use Array.prototype.forEach to get it directly rather than creating an empty array and digging forEach out of it.

This approach is usually used when you have an array-like object (like NodeList; has length, 0, 1, 2, etc. properties) but is actually not an array. The array-like object doesn't have the array methods, but if you can get the array methods to run with the appropriate this (achieved with call), they will work nonetheless.

Since here you actually have a real array rather than an array-like object, you can invoke forEach directly, e.g., lists.forEach(...).

icktoofay
  • 126,289
  • 21
  • 250
  • 231