Not understanding Implement map on a Prototype challenge

Tell us what’s happening:
I don’t understand what the required of this challenge. I changed the code many times and read the text of challenge but I got stuck!!!

My 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
var newArray = [];
for (let i = 0; i < newArray.length; i++) {

}
// Only change 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.16; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Implement map on a Prototype

Link to the challenge:

First of all, your loop won’t ever run, because the length of newArray is 0 (plus, you’ve initialised it twice).

The challenge gives you a hint to use this inside your myMap function. Have you tried to console.log(this)?

It looks like the challenge is asking you to write an array constructor Learn about Array.prototype here that maps over an array.

In the example, the myMap function is returning a new array with each item *2 (this is the callback function). Your myMap function is not working right now as you are trying to loop over an empty array.

In pseudo-code what the myMap function needs to do is:

change each item with the callback function
add to NewArray
return newArray```
1 Like

Yes, inside the function the output shows: [23, 65, 98, 5]
outside the function the output shows: undefined

Thank @emma-r-slight for your helping and welcome to our community!

So you have access to the array that’s passed into your myMap function now, using this. The challenge asks you to write your own version of JavaScript’s .map method, so you’d first have to understand what .map does: You use it on an array, and it goes through all items and modifies each item according to the provided callback function. Then it returns the new array.

You’ve already set up a for loop for this, but you have put in the wrong condition for how long the loop should run (newArray.length is always 0). Instead, it should iterate over the whole length of the array that’s passed in. Then, inside the loop, modify each item of the array with the callback function, and push it into the new array. Can you solve it from here?