Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's [] in [].forEach.call() [duplicate]

Tags:

javascript

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) {
    ...
});
like image 222
earllee Avatar asked Jun 29 '13 23:06

earllee


People also ask

What is meant by [] forEach ()?

Definition and Usage The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

What is array prototype forEach call?

The JavaScript forEach method (Array. prototype. forEach) is a function that iterates through an array and will execute a callback that is provided to it on each iteration. The forEach method was added in ECMAScript 5 specification and has full browser and node. js support.

What is return in forEach loop?

Using return in a forEach() is equivalent to a continue in a conventional loop.


1 Answers

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(...).

like image 186
icktoofay Avatar answered Oct 16 '22 21:10

icktoofay