24

I was just goin through the Electron API Demo code samples when suddenly a wild expression - which is completely foreign to me - appeared:

const links = document.querySelectorAll('a[href]');

Array.prototype.forEach.call(links, function (link) {
    // WWIII here
})

I definitely understand what this piece of code is doing but I am used to a syntax like this:

links.forEach(function (links) {});

So what exactly is the difference between those two? I have already read various StackOverflow threads about this topic but they are either ambiguous or don't answer the question at all. Some said it had something todo with array-like collections not being iteratable by .forEach() as opposed to Array.prototype.forEach.call(). Is that the only advantage of the overly tedious and long version?

Thanks in advance!

4
  • 6
    "Advantage" isn't the right word here. link is not an array, it doesn't have a links.forEach property. So, in order to use forEach on that value, you have to get a reference to Array.prototype.forEach somehow. May 2, 2017 at 17:12
  • [].forEach.call(links, link => ...) will work too. May 2, 2017 at 17:25
  • 3
    @FelixKling Actually NodeList.prototype.forEach is the thing in major browsers. So we no longer need call hack to iterate with forEach interface.
    – dfsq
    May 2, 2017 at 17:29
  • @dfsq: Ah, that's good news :) developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach May 2, 2017 at 17:31

3 Answers 3

38

"class methods" in JavaScript are actually functions defined on a prototype. That means that even if an object does not inherit from the Array prototype, you can call Array methods on it, as long as it follows the array structure (i.e.: It is an object with a length property and properties indexed by integers). However, the object holds no reference to Array.prototype, so you need to explicitly select Array.prototype as the object the method lives in.

The document.querySelectorAll function returns a NodeList, which is neither an Array nor inherits from the Array prototype. However, as a NodeList has a similar internal structure to an Array, you can still use the forEach function. But since NodeList does not inherit from the Array prototype, trying to use .forEach on a NodeList would raise an error (this is not exactly true - see the note at the end of my answer). For this reason, you need to explicitly state that you are calling a method from Array.prototype on the NodeList, and that is done by using the .call method from Function.prototype.

In summary:

Array.prototype.forEach.call(links, function(link) { /* something */ })

means:

Take the forEach function from Array.prototype and call it on links, which is a non-Array object, with some function as its argument.

Note that on recent versions of browsers, the NodeList prototype does provide a forEach method which works the same as the Array one, so the example from the Electron API is probably using the Array version for compatibility with older versions. If you have a web app and only care about supporting modern versions of Chrome and Firefox, you can just call forEach on your NodeList. In fact, since Electron updates about 2 weeks after whenever Chrome updates, it should be safe to use NodeList.prototype.forEach in Electron. :)

5
  • "trying to use .forEach on a NodeList would raise an error" - actually no, because NodeList does provide forEach.
    – georg
    May 2, 2017 at 17:30
  • @georg But only on recent versions of browsers. On older versions, it would fail. I'll edit my answer to reflect this. May 2, 2017 at 17:31
  • 2
    Thank you kind sir, this is one beast of an explanation :) May 3, 2017 at 15:19
  • Why does this not work: templates = document.getElementsByClassName("tem") templates.forEach(function (template, ind,obj) { for (var schluessel in werte) { template.innerHTML = template.innerHTML.replace('','')}? I get Uncaught TypeError: templates.forEach is not a function. I got it from here. I want to do variable replacement in html and use the classes to reduce the dom crawling. Array.prototype.forEach.call(templates, function (template) does the job.
    – Timo
    Aug 14, 2020 at 12:17
  • Best part for me was "as long as it follows the array structure (i.e.: It is an object with a length property and properties indexed by integers)". Clear condition for object to be array-like object so that I can call any Array methods by Array.prototype.XXX.call.
    – bob
    Mar 23, 2022 at 21:20
4

This is interesting question. Half a year ago I would say that link.forEach is not about shorter syntax, but it is actually not supposed to work. Then I would explain what it means that many of array methods deliberately generic, which means that their internal implementation only considers numeric indexes and length property of the this object, but doesn't care about it being Array instance. Basically what @Pedro Castilho said in his answer.

However, now I will say that these days evergreen browsers (except IE11, Edge, as of April 2017) already implemented NodeList.prototype.forEach convenience method so you no longer need to use .call hack or Array.from in order to just iterate NodeList with forEach.

So my summary: if you don't need to support IE, then use NodeList.prototype.forEach rather than Array.prototype.forEach. It might be the same internally, but cleaner conceptually. If you do need to support IE and you don't want to include one more pollyfill then use Array.prototype.call or better Array.from.

2
  • 1
    This is arguably a minor bug in the Electron sample app since the code runs in 'browser' that is guaranteed to have this function. There's no need for the hack and it's just confusing.
    – pvg
    May 2, 2017 at 17:33
  • Oh, if we know that we are in safe environment like Electron, then of course it's preferable to just use links.forEach. It's just not everyone knows about that yet..
    – dfsq
    May 2, 2017 at 17:36
3

This may be related to how the document.querySelectorAll returns a static NodeList rather than an Array.

Using the Array's prototype, you may still call the forEach, it is similar to operating on arguments.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.