-1

I was given the following solution to an exercise:

var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;
};

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

the idea is to build your own replacement for .map() method.

My problem is to understand the callback part. So far my understand of a callback, is a funct that is passed into another function (as an arg) and is called after something else.

I cannot see where is another function being passed in as the callback in the solution, so I'm struggling to understand the exercise, mainly: this.forEach(a => newArray.push(callback(a)));

Is there anyone who could clarify this for me?

Tiago Ruivo
  • 183
  • 1
  • 9

1 Answers1

1

You can easily visualize synchronous callbacks by replacing the call with the functions code itself.

In your function call, callback is equal to:

  function(item) {  return item * 2; }

If we insert that into this line:

  this.forEach(a => newArray.push(callback(a)));

we get:

  this.forEach(a => newArray.push(
     /*item = a*/
     /*return*/ a * 2;
   ));

Or in other words, for each a in the array, a * 2 gets pushed to the newArray.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • so this means that ```Array.prototype.myMap = function(callback)``` is expecting the return value of ```var new_s = s.myMap(function(item)?``` – Tiago Ruivo Nov 15 '19 at 11:30
  • Yes, if you call a function you get its return value back. – Jonas Wilms Nov 15 '19 at 11:31
  • I understand what you mean, but I'm still quite confused of how the return value of the callback funct is being passed into ```.push(callback(a))``` – Tiago Ruivo Nov 15 '19 at 11:39