Functions into Functions

Functions as Callbacks

Todd Motto by Todd Motto Google Developer Expert Icon Google Developer Expert
JavaScript Icon

Learn JavaScript the right way

Premium JavaScript courses to skyrocket your skills to the top.

5x Courses: Basics, Masterclass, HTML5 APIs, DOM, Testing with Jest.

Callback functions. Love them or hate them, they have their place in JavaScript and are worth learning about.

In fact you probably use them all the time.

A callback function is just a function, but passed to another function.

It waits to be called by the function you pass it into, and can give you some data back.

A simple example, passing function() {} into addEventListener:

element.addEventListener('click', function() {});

What happens next? We sometimes want to access the event given to us inside addEventListener, so let’s ask for it as a parameter:

element.addEventListener('click', function(e) {
  console.log(e.target);
});

Our callback function simply “waits” to be called by the event listener, we do not call the function. That’s the important bit.

The addEventListener will call the function when the 'click' event fires.

Behind the scenes, the event object is passed back to us and we can access properties such as e.target.

Let’s create our own. Our example will be invoked when our object is created.

Taking our earlier function:

function makeDrink(name, price) {
  const drink = {
    name,
    price
  };
}

makeDrink('Lemonade', 299);

We can get our newly constructed object when it’s created by supplying a callback, and then passing in the object whilst calling the function:

function makeDrink(name, price, fn) {
  const drink = {
    name,
    price
  };

  fn(drink);
}

makeDrink('Lemonade', 299, function(drink) {
  // use `drink`
});

This is known as a “synchronous” callback, because it’s executed right away.

Typically callbacks, for example in Node.js, are asynchronous - and happen after a period of time (for example after something is saved to a database).

Callbacks allow us to pass data around and can be an important design decision, especially in third-party libraries and with asynchronous tasks.

More commonly, you would likely opt for using something like a JavaScript Promise and then .then() signature for asynchronous tasks.

Short and Long Syntax

« Implicit and Explicit Return Statements

Hiding The Details

Closure and Scope in Functions »