Functional Programming - Implement map on a Prototype

Tell us what’s happening:
Describe your issue in detail here.

i cant get anything into my head.
which function is passed as argument callback .what is it doing with “s.myMap” 'const_s 'or ‘item’. Please someone explain in detail what’s happening.

Your code so far

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

Array.prototype.myMap = function(callback) {
  let newArray=[];
  // Only change code below this line
  for(let i=0;i<this.length;i++){
    // console.log(this[i]);
    newArray.push(callback(this[i]))
    console.log(callback(this[i]))
  }
  // Only change code above this line
  return newArray;
};

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Functional Programming - Implement map on a Prototype

Link to the challenge:

This code is taking an array (which is an Object) and multiplying each number inside it with 2.

First look at the last line:

A function “callback” is being sent here to myMap which you defined earlier to be a function that belongs to all Arrays. As s is an array of type Array, when you try to call myMap in this line, it uses the previously defined code to run the function “callback” that you are giving it here.

So basically, this code creates a new Array object function called myMap and calls it once.
The Array object we have is s.
The callback is the input to myMap. (That’s the function down in the last line that multiplies a number by 2)

Wishing myMap, each number in the Array object gets the callback function applies to it.

The resulting new array is returned.

function(item)
{return item * 2;

is the above function passed as callback in myMap function??

Yes it is . You can see that because the function is inside the brackets and the bracket is immediately to the right of the word myMap

1 Like

ohkk i got this now.Thank youu!

1 Like

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