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

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?

3 Likes