Home » Javascript » How to create a custom forEach using JavaScript

How to create a custom forEach using JavaScript

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have this code that creates a custom forEach, ‘myForEach’, and then I attach that to the Array prototype. I am following along to an example.

“`JAVASCRIPT

const myArray = ['red', 'green', 'blue'];

Array.prototype.myForEach = function(func) {
    for(let i = 0; i < this.length; i++) {
        func(this[i]);
    }
}

myArray.myForEach(function(color) {
    console.log(color);
})

“`
He creates the custom loop to accept a function. However, when he calls the ‘myForEach’, he adds the ‘name’ param. How does this work? Where is the ‘name’ param coming from?

Answers: