What is "callback" work?

// The global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
  var newArray = [];

  // Add your code below this line
  for (let i = 0; i < this.length; i++) {
    newArray.push(callback(this[i]));
  }
  // Add your code above this line

  return newArray;
};

var new_s = s.myMap(function(item) {
  return item * 2;
});

How does this code work(step by step)? // Why is there a ‘‘callback’’ parameter ?

from
Implement map on a Prototype

1 Like

A “callback” is just a function. It is a function that is passed to another function for it to use. It is very common with async functions (run this function after you’re done) and prototype methods (use this function for whatever you are doing).

Your case is the latter, your own map function. You are saying, when you map, use this function. You call your mapping function here:

var new_s = s.myMap(function(item) {
  return item * 2;
});

You are passing the function as the parameter:

function(item) {
  return item * 2;
}

That is the parameter being passed to myMap.

In myMap, you have:

Array.prototype.myMap = function(callback) {

So, the reference (address) to that anonymous function that you passed in is stored in the variable callback and can be used in myMap.

Does that help?

7 Likes

If I am understanding this right, the callback function is a reference to whatever function instructions we define later when actually using the myMap function (like when we ask it to return item *2).

So every time we iterate, we are performing those function instructions (whatever they may be) on the current item, before we push it to the new array. And those function instructions could be something totally different depending on the user’s needs.

Is that correct, or am I missing something?

p.s thanks for your comment, it really helped me understand this better

1 Like

If I am understanding this right, the callback function is a reference to whatever function instructions we define later when actually using the myMap function (like when we ask it to return item *2).

Sure. More generally, a callback is just a function you pass into a second function for that second function to use later.

So every time we iterate, we are performing those function instructions (whatever they may be) on the current item, before we push it to the new array. And those function instructions could be something totally different depending on the user’s needs.

Yep. That’s the nice thing of having passing in a callback function. We could write separate a mapping doubling, squaring, getting the absolute value, adding 2, converting to a string, etc., etc., etc… but that would get ridiculous. Instead we just pass in a function and it tells it what to do for each member.

1 Like

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