Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one use Array.prototype.forEach.call(array, cb) over array.forEach(cb)?

I've just been looking over some photos from this year's ng-europe conference and noticed a slide I think might show some code from the upcoming Angular 2. See here:

Example from ng-europe

(Source: https://plus.google.com/u/0/photos/+ThierryLAU/albums/6073085583895256529/6073092865671487010?pid=6073092865671487010&oid=105910465983441810901)

What I don't get is this:

Why is the author of this code using Array.prototype.forEach.call(array, cb) in preference to the shorter and (in my opinion) equivalent version array.forEach(cb). The only reason I could imagine would be performance implications.

Does anybody know of another difference? Or am I maybe right with my performance guess?

like image 614
NicBright Avatar asked Oct 24 '14 10:10

NicBright


2 Answers

There are number of Array-like objects which look like arrays, however are not. To name some:

  • arguments
  • children and childNodes collections
  • NodeList collections returned by methods like document.getElementsByClassName and document.querySelectorAll
  • jQuery collections
  • and even strings.

Many array prototype methods are generic by purpose, which means that their internal implementation does not depend on context this to be an instance of Array constructor. This allows to call those methods in the context of other objects which "look" like arrays. Namely, looking like an array means that the object have numeric keys and length property.

Here is one useless example of how you can call Array.prototype.join on custom array-like object:

Array.prototype.join.call({0: 'one', 1: 'two', length: 2}, ' ');

Above will output string "one two". However supplied object is clearly not an array.

like image 189
dfsq Avatar answered Oct 08 '22 10:10

dfsq


It is being a bit defensive against element.attributes or element.children not being arrays.

like image 28
Daniel A. White Avatar answered Oct 08 '22 10:10

Daniel A. White