Implement prototype.map

Tell us what’s happening:

Cant understand how the prototype.map works. I checked the solution and its still not clear for me. This is how it should look like.

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;
});

But the moment when its written

newArray.push(callback(a))

makes me crazy, how It works?

Your code so far


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

Array.prototype.myMap = function(callback){
var newArray = [];
// Only change code below this line

this.forEach((element)=> {
  newArray.push(element)
})

// Only change code above this line
return newArray;
};

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

console.log(new_s)

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Implement map on a Prototype

Link to the challenge:

Generally map takes each of the element in array and passes it, one-by-one to specified function. It returns array composed from the values returned by that function.

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

For each element, which will be here temporally called a, new value is pushed to the newArray. That value is the result of the function callback, to which is passed a - callback(a).

And callback is the function which is passed when myMap is being called. callback is called internally from the myMap function, so that’s actually function being passed, not the return value of function.