๐Ÿ“ฒCallback Functions

Callbacks and higher-order functions are some of the most misunderstood concepts in JavaScript. In this post, we will become familiar with them to write pro-level code as JavaScript engineers.

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some sort action.

Callbacks: Using a Function as an Argument

What is a callback?

  • A callback is always a function that is being passed into another function.

let foobar = function (callback) {
  console.log("foo");
  callback();
  console.log("bar");
};

let sayHello = function () {
  console.log("hello");
};

foobar(sayHello); // prints
// foo
// hello
// bar
  • Although we named our parameter callback, we could name it anything we like.

  • Anonymous Callback : When we use a function expression directly.

  • Typically we want to assign our callback to a name if we plan on using it multiple times, an anonymous callball is better if it's just single use.

A More Interesting Example

  • Variable expression function being passed in as an argument.

  • Math.sqrt built in function being passed directly in as an argument.

Refactoring for an Optional Callback

  • We can add in a conditional to make the callback optional. (This is a very common pattern in Javascript!)


Callback Functions as First Class Objects

  • First-Class Object : A type that supports the same basic operations as most other types. (i.e. Numbers, Strings & Booleans)

  • First-Class Objects must be able to do three things:

    • They can be stored in variables.

      • Function Expression Notation.

    • They can be passed as arguments.

      • Callback Functions.

    • They can be returned in functions.

  • As we have just proved above, functions are indeed first-class objects!

  • Higher-Order Function : A function that should either accept another function as an argument, or return a function as an output.

  • Callback Functions are passed into Higher-Order Functions.


Callback Functions Demo

Interesting Interaction.

Objectives

Callbacks

Given multiple plausible reasons, identify why functions are called โ€œFirst Class Objectsโ€ in JavaScript. Given a code snippet containing an anonymous callback, a named callback, and multiple console.logs, predict what will be printed Write a function that takes in a value and two callbacks. The function should return the result of the callback that is greater. Write a function, myMap, that takes in an array and a callback as arguments. The function should mimic the behavior of Array#map. Write a function, myFilter, that takes in an array and a callback as arguments. The function should mimic the behavior of Array#filter. Write a function, myEvery, that takes in an array and a callback as arguments. The function should mimic the behavior of Array#every.

Last updated

Was this helpful?