Understanding callbacks

Hi everyone,

So I have started learning JavaScript on FCC, which is going okay I think :slight_smile:

I’ve now come to the part about functional programming, but I’m kinda getting stuck in understanding how callback functions work.
Especially now that the course asks me to write my own myMap() and myFilter() functions. I have looked up the solution (as below), but I still don’t quite understand how it works.

Could someone give me some step by step indication what actually happens in the below code?

let s = [23,65,98,5];

Array.prototype.myFilter = function(callback) {
  var newArray = [ ];
  // Add your code below this line
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i]) === true) {
      newArray.push(this[i]);
    }
  }
  // Add your code above this line
  return newArray;
};

var new_s = s.myFilter(function(item) {
  return item % 2 === 1;
});

A callback is just a function that is passed into another function to be used by that other function. That’s all, it’s nothing magical. And I think writing your own version of the prototype methods is an excellent way to understand them. And yes, they confused the heck out of me at first too.

In the example you give, you pass in an anonymous function:

function(item) {
  return item % 2 === 1;
}

This gets accepted as a parameter and called “callback” - but it could have been called anything. I might have called something less generic, like “testForAcceptance” since this is a filter method.

Anyway, that test is just applied to determine if we should add that element to the new array.

Perhaps if you put in some log statements into your code you can see a little better what is happening:

  for (let i = 0; i < this.length; i++) {
    console.log('checking element', this[i])
    console.log('  element passes test?', callback(this[i]))
    if (callback(this[i]) === true) {
      console.log('  adding element', this[i], 'to the new array')
      newArray.push(this[i]);
    }
  }
1 Like

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