Callback functions in javascript

Can anyone help me in understanding this code step by step?
I’ve tried my best but was unable to simplify it in my understanding.

function myForEach(array, callback) {
  for (let i = 0; i < array.length -1; i++) {
    callback(array[i]); // This is when the callback function gets called, or executed
  }
}

// You would call it like this:
const myArry = [2, 3, 4, 2];
myForEach(myArry, (item) => {
  console.log(item + 2); 
})

This is the website where this code above is from Briggs Elsperger

The blog post explains the code. Do you have a specific question about something you do not understand?

myForEach is a function that takes an array and a function. It loops the array, calls the function, and passes the array elements as arguments to the function.

myForEach is called and is passed an array and a inline anonymous function (i.e. inside myForEach callback is (item) => { console.log(item + 2); }).

1 Like

I don’t understand this part ```
callback(array[i])

Can you explain it to me?

callback is the function second argument of myForEach, it is called with array[i] as argument

1 Like

In your example, the function is passed an inline-function when it’s called - which makes it a little hard to read. Maybe rewriting it like this makes it clear what the callback argument is.


// You would call it like this:
const myArry = [2, 3, 4, 2];
const myFunction = (item) => {
    console.log(item + 2)
}; 

myForEach(myArry, myFunction)
1 Like

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