Javascript Problems – Create my own Array.prototype.forEach() method – myForEach()

The purpose of this exercise is to create my own Array.prototype.forEach() method – myForEach(). According to the MDN Developers page for Array.prototype.forEach(), “The forEach() method executes a provided function once for each array element”.

I use the same sample data sets as I did or the myMap() method.  Whereas myMap() modifies each element in the array, and returns a complete array, myForEach() processes each element in the array separately.

On line 3, I add a new myForEach() method to the array object.  The method takes in a function as its single argument.  It then runs through each item in the array that calls the method, and applies the function to each item.

On line 22, I apply the myForEach() method to the numbers array ([1,2,3]), passing in the addOne function as an argument.  It console.logs out the following output:

On line 26, I apply the myForEach() method to the letters array ([“a”, “b”, “c”]), again passing in the addOne function as an argument.  It console.logs out the following output:

Finally, on line 30, I apply the myForEach() method to the sales array([100,225, 15]), passing in the addTax function.  For the output, it console.logs the following:

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *