1

I'm diving into Javascript callbacks and stuff. I came around the forEach() function. The functioname says it all, loop through each object in a list.

When I look into the documentation I see the following syntax:

arr.forEach(callback[, thisArg])

And the documentation also mentions the parameters

currentValue
index
array

I stumbled upon an easy example of a forEach implementation:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
     console.log(index + 1 + ". " + eachName);
});

And this gives me the obvious output:

 "1. Mike"
 "2. Stacy"
 "3. Andy"
 "4. Rick"

I can live with the behaviour about everything and the result it gives, but I want to know why this is working and I'm confused about this

...function (eachName, index)...

When and where or how are eachName and index being filled with the correct value? Or how can I see how forEach is implemented, cause I'm guessing that this one is doing the magic here? Or am I missing an important concept here?

1
  • 1
    ECMAScript® 2015 Language Specification -> Array.prototype.forEach(), or in the annotated ES5 Commented Oct 27, 2015 at 13:24

2 Answers 2

2

In the link to MDN that you provided, you find the answer:

The three parameters (currentValue, index, array) are the parameters of the callback function (arr.forEach(callback[, thisArg]). To display it in your example:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (currentValue, index){
     console.log(index + 1 + ". " + currentValue);
});

So when forEach is run, a lot of things happen (have a look at the polyfill on the MDN page), but at some point, forEach will loop through the items in the array and call the callback you provided, with the arguments mentioned above. A simplified version would be:

Array.prototype.forEach = function(callback, thisArg) {
    // ...
    for(let i = 0; let i < this.length; i++) { // "this" refers to your array here
        // Here the arguments are passend in:
        // currentValue = this[i]
        // index = i
        // array = this
        callback.call(thisArg, this[i], i, this);
    }
    // ...
};
Sign up to request clarification or add additional context in comments.

Comments

1

This is a simplification of an actual .forEach() implementation, only to give the basic idea of what's happening.

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

Basically it loops through the array and calls the function with the correct parameters at each iteration.

The actual implementation is engine-specific and (most likely) not native JavaScript.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.