Callback confusion

callback is an argument but the question is how it’s working as a function after invoke the myMap function ?
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
for(let i=0;i<this.length;i++){
newArray.push(callback(this[i]))  
}
// Only change code above this lin
return newArray
};

var 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/92.0.4515.107 Safari/537.36

Challenge: Implement map on a Prototype

Link to the challenge:

It’s working as a function because the argument that you pass into myMap is a function. Slightly re-written:

var myCallback = function(item){
  return item * 2
}

var new_s = s.myMap(myCallback);
1 Like

I’ve to revisit functional programming previous lessons :sweat_smile:

Firstly, callback isn’t some kind of “magic” word. You can name parameters of your functions as you wish but at the same time there are conventions / industry standards which will help you and others to read and understand each others code more easily and faster. Read about callback here

Secondly in JavaScript functions are “first-class objects”. You can pass functions into other functions as an argument and return functions from functions meaning the result of execution of your function would be another function which you’ll be able to call later in your code.

Finally, this has nothing to do with OOP

I know that :expressionless:

Ohhh not OOP , I’ve to revisit the functional programming previous lessons

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