L4M3
L4M3

Reputation: 11

How do the arguments of callback functions work?

I just started with javascript and I can't really comprehend how callback functions work. It may sound dumb but I have some questions. I'll delete if it's not ok.

If a callback function is a function passed as an argument to another function, what happens to the arguments of the callback function?

Will using a callback function execute it twice(once when it's used as an argument and one when it's declared)?

Also, I can't wrap my head around how in the photo attached below the callback function arguments take the values of the elements in the array.

enter image description here

Upvotes: 0

Views: 114

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

By Taking the example of your snippet, we see that logPerson is a function. Also we are using Array.prototype.forEach to loop over an array of people.

Now forEach takes a function as a argument, which it invokes with the arguments as item value and index for each iteration.

So when we pass logPerson as argument to forEach, this function is invoked with the arguments that forEach passed to its callback

A simple implementation of forEach could be like

Array.prototype.forEach = function(callback) {
    const arr = this;
    for(let i = 0; i < arr.length; i++) {
        callback(arr[i], i);
    }
}

The other way to write your example was

let people = ["mario", "luigi", "rui"];

people.forEach((person, index) => {
   console.log(`${index} - hello ${person}`);
})

Upvotes: 2

Related Questions