Tell us what’s happening:
Could someone help me to understand what ‘callback’ represents in this problem? I understand I have to mimic Array.prototype.map() but I’m not sure where to begin. If I used a for loop or forEach(), what exactly would I be iterating on?
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_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype
“callback” is a function that you are sending into the function. In this case, it is:
function(item){
return item * 2;
}
as defined at the bottom of the app, when you call myMap. I know it seems weird, but you do this all the time with these methods and with asynchronous events. Think, how is this function used in map. What does it need to do with it to accomplish what map does.
Let us know if you need more hints.
1 Like
@kevinSmith Thanks for the clarification! It makes sense now and i was able to solve it with:
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
for (var i=0; i<this.length; i++){
newArray.push(callback(this[i]));
}
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
console.log(new_s);
1 Like
Cool, it takes a little getting used to. But like I said, you’ve been using callback all over the place, sending them. This showed you how to take in and use a callback. This will become important later on. CBs are a very cool and necessary feature of JS.
1 Like
You surely know how to break down or explain problems for better understanding…