Implement map on a Prototype: callback?

Hello,

I am having difficulties to understand the callback from the solution for this problem; Implement map on a Prototype

Any idea where I need to start to understand the callback?
Thank you!




So far, I was able to write down the code by myself like below:

Screen Shot 2020-03-07 at 4.22.22 PM

3 Likes

I think that I found a helpful link for this; What the heck is a Callback?

It would be thankful if someone explains the flow of the callback from the problem…

1 Like

The Array.prototype method defined has a parameter named callback. It can be named anything (like fn or whatever) and you can pass it whatever you like, but in this case, it should be passed a function so it can be call inside the method.

// Method definition
Array.prototype.myMap = function(callback) {
  // call the function and do something
  callback(doSomething);
}
// Method invocation
ArrayToMap.myMap(function(item) {
  return item * 2;
});

So the callback parameter is passed a function, in this case, an anonymous function

function(item) {
  return item * 2;
}

So when myMap is invoked (called/ran) the callback parameter (which is just a variable) contains the anonymous function from above.

callback = function(item) {
  return item * 2;
}

Here it is with some logs

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

Array.prototype.myMap = function(callback) {
  console.log(callback);
  // ƒ (item) {
  //   return item * 2;
  // }

  console.log(typeof callback)
  // function
};

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

I was confused with this one as well. I got to exactly the point you did. A few things were eye openers to me.

First, if you console.log(this) within the .myMap function, you get the whole array. This was not really ever discussed within any of the previous lessons that I can recall. Where is ‘this’ initialized? Perhaps someone can explain that to me. You seem to have had the same realization and used it in your loop.

The second realization I had was that you need to execute the function that is passed into the .myMap prototype function (hopefully I described that correctly). What I forgot was that when you make a variable equal to a function, you can execute/call the function using the variable name:

let add = function(val){
return val + 4
}
//you can then use add() as a function
console.log(add(5)) // should = 9

Given those two things, you should be able to use the callback variable name – passing in the this[i] as an argument. It will return whatever the operation within the callback is programmed to do. You can then .push() that value to the array.

newArray.push(callback(this[i]));
1 Like

The challenge should get updated (issue, PR). There is some ongoing talk in the PR about the this issue.


1 Like