Logic behind forEach and callback functions

So, because the result included “a apple”, the grammar was driving me nuts.
I created an “if statement”; however, I don’t completely understand the logic of how this code is working (as far as the element parameter). It seems there are different ways to use a callback. Could someone please help me understand? Here’s my code below:

const fruits = [‘mango’, ‘papaya’, ‘pineapple’, ‘apple’];

const allFruits = element => {
if (element != ‘apple’) {
console.log(I want to eat a ${element});
} else {
console.log(I want to eat an ${element});
}
}

fruits.forEach(allFruits);

foreach is passing the elements to the callback parameter (element), one at a time and in order

1 Like

Thank you. So, allFruits is the callback with a parameter of “element”, which forEach passes to after being told to loop through the “fruit” array?

no, foreach calls the callback function for each element in the list/array.

lets build our own very naive implementation:

function theForEach(theArray, theCallBackFunction){
  for (let i = 0; i < theArray.length; i++){
      theCallBackFunction(theArray[i]);
  }
}

const myArray = [1, 2, 3];

const myCallBack = element => {
  console.log(element);
}

theForEach(myArray, myCallBack);

theForEach represents the forEach method you currently use

i used slightly different syntax, otherwise i had to introduce a lot of new concepts

2 Likes

That really cleared things up, thank you so much. So you just used the “for loop” opposed to forEach?

no, i wrote my own implementation of forEach. Foreach is juts a higher order function, abstraction to keep your code more readable and less repetitive.

The syntax should have been:

myArray.theForEach(myCallBack)

But that would introduce too many new concepts for you. So i tweaked it slightly.

3 Likes

Okay, gotcha. I really appreciate you taking the time to help me :slight_smile:

under the hood, .forEach probably uses a for loop or something similar. I just showed you a very naive implementation to get the hang of it

1 Like

Your implementation definitely helped out a lot, thanks!