Callback functions

By on

When we are using functions, we can pass arguments, arguments can be strings, booleans, integers, arrays, etc… they can also be functions, this is called a callback function. A callback acts like a function pointer which is invoked or called back at some point.

Let’s take a simple example:

function applyCB(string, callback) {
  callback(string)
}

Notice that callback parameter is not invoked, since it doesn’t have the invocation operator (pair of parentheses). Inside applyCB is when the callback function is invoked. Also, notice that callback has a parameter string when it is called.

Let’s see it in action!

applyCB("Javascript", function(str) {console.log(str + " is awesome!")})
//Javascript is awesome!

When applyCB is called, it is passed 2 arguments: string and callback; string which is Javascript and callback which is function(str) {return str + “ is awesome!”}, notice that this is an anonymous function (a function without a name).

The callback can also be stored as a variable and used as an argument:

var isAwesome = function(str) {
  console.log(str + " is awesome!")
}

applyCB("Javascript", isAwesome)
//Javascript is awesome!

Understanding callbacks is helpful when using methods that take them as a parameter. It’s also important to understand how closures work.

In this example, obj has a property called addPropTo, which also happens to be a function that takes array as a parameter. It uses the map method which takes a callback as a parameter. To see what the map method does, read more about it here.

var obj = {
  prop: "is awesome!",
  addPropTo: function(array) {
    return array.map(function(item) {
      return item + ' ' + this.prop
    }, this)
  }
}

console.log(obj.addPropTo(["Javascript", "Learning"]))
//["Javascript is awesome!", "Learning is awesome!"]

Notice that the map method takes 2 parameters, the callback function function(item) {return item + ‘ ‘ + this.prop} and thisArg this, read more about the second optional parameter thisArg here.

Each function call gets it own this context. So the callback that is passed as parameter in the map method is looking for it’s own prop, so we pass a second argument (this) to use as this when executing callback.

There are different ways of solving the situation above. Read more about it here.

More about Javascript Callbacks

Understand Javascript Callback Functions and Use Them

Understanding closures, callbacks and promises

Higher Order Functions

<p class=store> Feedback </p>