JavaScript Callbacks: Higher-order Functions

Nitin Gupta
Rocketium
Published in
5 min readAug 22, 2020

Callback functions are probably the most widely used functional programming technique in JavaScript, and you can find them in just about every piece of JavaScript as well as jQuery code, yet they remain mysterious to many JavaScript developers. These are a little confusing to understand but once you get a taste of it, it’s hard to resist yourself from using them. In this article we will try to understand the concept of callbacks in an easy and much a simpler way.

Imagine we have a variable in a “function” which we want to use in some “other function”. We can pass it as a parameter in the “other function” call and hence use it there. The variable can be String, Array, Number, Object etc. But what if the variable can be a function? Yes you read it right.

In JavaScript, functions are first-class objects, that is, functions are of the type Object and they can be used in a first-class manner like any other object (String, Array, Number, etc.) Since they are in fact objects themselves, they can be stored in variables, passed as arguments to functions, created within functions, and returned from functions.

Now because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later. This is the essence of using callback functions in JavaScript. Thus implementing callback functions is as easy as passing regular variables as arguments.

Where and Why to use callbacks?

Before learning more about callbacks, we will get an idea where we can use callbacks in our code so that we can get a better idea about it, for they will allow you to:

  1. Do not repeat code (DRY — Do Not Repeat Yourself)
  2. Implement better abstraction where you can have more generic functions that are versatile (can handle all sorts of functionalities)
  3. Have better maintainability
  4. Have more readable code
  5. Have more specialized functions.

Also Note the following ways we frequently use callback functions in JavaScript, especially in modern web application development, in libraries, and in frameworks (React.js, Node.js etc):

  • For asynchronous execution (such as reading files, and making HTTP requests)
  • In Event Listeners/Handlers
  • In setTimeout() and setInterval() methods
  • For Generalization: code conciseness

What is a Callback or Higher-order Function?

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the “otherFunction”. See in the below example.

How callbacks work?

When we send the callbacks, neither they execute as in the parameter nor automatically in the “otherFunction”. Rather since they are a function only, we need to call them in the “otherFunction”. While calling them, we can send the local variables of the “otherFunction” in the callback function and thus, the local variables of “otherFunction” can now be used in the function passed as callback. Taking the above example we can see that we have defined a function named as “genericPoemMaker”. Next we define a function named “getUserInput”. In last we have called “getUserInput” and passed “Nitin” (a string), “Gupta” (a string), “Man” (a string), “genericPoemMaker” (a function) as parameters. Note how we have just passed the “genericPoemMaker” function and received it in the “getUserInput” function defination as callback. Then we concatenated the first and last name and sent it as parameters in callback along with gender. (Note: Here I have used fullName to show you that a local variable of “getUserInput” can be sent in callback). Now callback is none other than “genericPoemMaker” itself and thus it gets called and we get the desired output.

“Callback Hell” Problem And Solution

In asynchronous code execution, which is simply execution of code in any order, sometimes it is common to have numerous levels of callback functions to the extent that you have code that looks like the following. The messy code below is called callback hell because of the difficulty of following the code due to the many callbacks. I took this example from the node-mongodb-native, a MongoDB driver for Node.js. The example code below is just for demonstration:

You are not likely to encounter this problem often in your code, but when you do — and you will from time to time — here are two solutions to this problem.

  1. Name your functions and declare them and pass just the name of the function as the callback, instead of defining an anonymous function in the parameter of the main function.
  2. Modularity: Separate your code into modules, so you can export a section of code that does a particular job. Then you can import that module into your larger application.

Final Words

Hope I was able to fulfill your purpose of coming here and you are not thinking that it was a waste of your time. This article was to give you a basic idea of callbacks to get you started. JavaScript callback functions are wonderful and powerful to use and they provide great benefits to your web applications and code. You should use them when the need arises. Look for ways to refactor your code for Abstraction, Maintainability, and Readability with callback functions. Real learning comes by doing. Try implementing it in your code yourself. See you next time!

--

--

Nitin Gupta
Rocketium

Elevating digital realms with a full-stack touch, merging design finesse with product mastery. I write about JS and my journey as a developer