Why did I have to use another parameter inside of the forEach method?

I have a doubt about the code that I created for one of the code challenges I was working on…when I created the new function called acceptEverything, I used a forEach method and according to the solution had to use a different parameter (in this case e) than the rest of the code…why?

const veggies = ['broccoli', 'spinach', 'cauliflower', 'broccoflower']; const politelyDecline = (veg) => { console.log('No ' + veg + ' please. I will have pizza with extra cheese.'); } let declineEverything = (arr) => { arr.forEach(politelyDecline) }; acceptEverything = arr => { arr.forEach((e) => {console.log(`Ok, I guess I will eat some ${e}.`)}); }; console.log(acceptEverything(veggies)) console.log(declineEverything(veggies));

When you pass arr into your function, you are passing the array to your function so that the function has something to loop over. When you use an iterator method (like forEach, filter, map, reduce), the variable you create for the arrow function inside of it represents the current element of the array at each stage of the loop. So one by one, the e will point to broccoli, spinach, cauliflower, etc.

You can actually call e whatever you want. It doesn’t matter what its name is; it will always refer to the current array element.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.