Implement map on a Prototype. Is that a loop?

what is the purpose of this function?

new_s called myMap with the result returned (item * 2), at here why we don’t push to an array -> that is a result.

var new_s = s.map((item) => item*2);
return new_s;

But, we used array s called myMap with parameter is each item of s, and in myMap, callback is a function.

console.log(callback);// function (item) { return item * 2; }

and then, I must be do something to return an array -> at this time, that is a final result.

I feel confused and conflict and I think that’s a loop. Is it right?

Please explain it to me!
Thanks!

Your code so far


// the global Array
var s = [23, 65, 98, 5];

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

};

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


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype

map() already takes an array, change each item using the callback function passed in, and return the changed array.
map() is already defined so you don’t see this

You need to create something that has the same functionality

I know about map, but i want to ask about myMap that is a loop?

myMap is not a loop, inside it you can use a loop (but is not the only way) to have the desired result

As I talked on top :

we used array s called myMap with parameter is a function.

console.log(callback);// function (item) { return item * 2; }

and then, I must be do something to return an array .

Why do we do everything become complex? And I’m stuck here.

It is an exercise
Inside myMap you need to take the array (you can reference the array with this), apply the function callback to each element to change it, and return a new array with the elements changed

map/myMap already returns or should return an array, you don’t need to use pushoutside the method because the method already returns an array with the items changed

callback is always a function, both map and myMap use callback to change the items of the array

You can use a loop inside myMap, sure

2 Likes

The challenge is finding the way how map is working.
The purpose is the way to use callback and the array loop.

Okay, I think i research about it deeply.
Anyway, thanks for your help! @ilenia