benhowdle89
benhowdle89

Reputation: 37464

How does forEach actually work on a NodeList

Very aware of the method:

[].prototype.forEach.call(aNodeList, function(node){
     // manipulate node
});

So, inside the forEach method, this will point to an array (which, in this case would be a NodeList). So you can use Array methods on the array-like NodeList.

I get this, but what I'm a little confused about is how this actually works? ie. why can't I do aNodeList.forEach() but I can call forEach on the Array prototype and it work? How can array methods work on an array-like object?

This question may not actually have an objective answer, just very curious.

Upvotes: 3

Views: 93

Answers (1)

tckmn
tckmn

Reputation: 59273

The native implemenation of forEach is something like this (this is greatly simplified, though):

Array.prototype.forEach = function(f) {
    for (var i = 0; i < this.length; i++) {
        f(this[i]);
    };
};

But, NodeLists can be looped through the same way! So if you call Array's forEach on a NodeList, it will behave the same way.

In fact, I could even create my own array-like object, and use Array's forEach on it!

> Array.prototype.forEach.call({length: 3, '0': 'zero', '1': 'one', '2': 'two'}, function(x){ console.log(x); });
zero
one
two

As to why there's no forEach on NodeLists, it's because it doesn't extend Array's prototype.

So why doesn't NodeList just have its own forEach implementation? Well, the answer basically boils down to "Because the people who made the JavaScript implementations didn't make one."

Upvotes: 6

Related Questions