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:

1 + 1 = 2
2 + 1 = 3
3 + 1 = 4

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:

a + 1 = a1
b + 1 = b1
c + 1 = c1

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:

Item Price: $100 + 10% tax of 10.00 = Total of: $110.00
Item Price: $225 + 10% tax of 22.50 = Total of: $247.50
Item Price: $15 + 10% tax of 1.50 = Total of: $16.50

 

// create forEach from scrap

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

function addOne(item) {
    console.log(item +  " + 1 = "+ (item+1));
};

function addTax(item) {
    // add 10% sales tax
    console.log (`Item Price: $${item} + 10% tax of ${(item*0.1).toFixed(2)} = Total of: $${(item*1.1).toFixed(2)}`);
};

const numbers = [1,2,3];
const letters = ["a", "b", "c"];
const sales = [100,225, 15];

const output = numbers.myForEach(addOne);
// 1 + 1 = 2
// 2 + 1 = 3
// 3 + 1 = 4
const output2 = letters.myForEach(addOne);
// a + 1 = a1
// b + 1 = b1
// c + 1 = c1
const output3 = sales.myForEach(addTax);
// Item Price: $100 + 10% tax of 10.00 = Total of: $110.00
// Item Price: $225 + 10% tax of 22.50 = Total of: $247.50
// Item Price: $15 + 10% tax of 1.50 = Total of: $16.50

 

 

Leave a Reply

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