Sitemap

Javascript Callback Functions

6 min readNov 22, 2021

--

It’s rare in my own life that I’m ever doing just one thing at a time. I’m usually trying to prioritize what needs to be handled, so I might have a list to work off. Yet, I still end up reorganizing and juggling the big things while pushing off the smaller and easier tasks; of course the goal is to try to quickly get back to those small tasks in the end so I can wrap up my day. Ultimately, failing to manage the chaos and properly organize how my day will go causes delays and other major issues. Coding in Javascript can be a lot like that as well. We expect our code to do a lot of things to make our lives easier, but it has to process the functions in a certain way and then often ‘call-back’ other functions to successfully deliver the experience we planned as developers in the correct sequence.

The Callback Function

When JavaScript reads through the code it moves down sequentially from the top. However, functions are executed in the sequence they’re called, and not in the sequence they’re defined. A callback function is specifically when a function gets passed as an argument into another function. This process works in our code because, in Javascript, functions have the properties of first class objects. The callback does not use its own set of parenthesis when being set as an argument because we do not want to invoke it ourselves directly, we are allowing the function it is nested within to handle the call. The functions that take callbacks as arguments are called higher-order functions. Using callbacks are great when using simple code statements, such as working to get a welcome String to be instantly logged into the console.

Synchronous Callback Example 1:

function hello(name) {
console.log(`Hi my name is ${name}`);
}

hello('Greg'); // Hi my name is Greg

Notice the bolded characters above help show how we can recognize the Callback function syntax even if we were to write it as an arrow function:

() => {}

This is the structure you will find inside of advanced functions such as Event Listeners. Remembering this structure is an excellent way to identify callbacks in more concisely written code.

Synchronous Callback Example 2:

We could look at another type of synchronous callback function that is hiding in plain sight. While working with arrays, we often will use .forEach() to iterate through the index of elements and perform some action. The array.prototype.forEach() function takes in another function, which is then processed for each index in order, one at a time, without waiting for other code to run.

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];months.forEach((eachMonth, index) => {console.log(`${index+1}` + '. ' + eachMonth);});// Returns all 12 months with the corresponding month numerals

We will more immediately recognize the function when we write this out in a more verbose way:

...
months.forEach(function(eachMonth, index){
console.log(index + '. ' + eachMonth);});

Javascript Under The Hood

Get Greg Banks’s stories in your inbox

Join Medium for free to get updates from this writer.

The Javascript language is single threaded, so it can only process one event at a time and the remaining events are blocked in that moment. The call-stack keeps track of the events and the event-loop processes the current function before moving on to the remaining code.

Press enter or click to view image in full size
https://www.webdevolution.com/blog/Javascript-Event-Loop-Explained

Asynchronous Callbacks are one way to tell JavaScript to wait to call functions until after some other function has occurred in order to prevent problems of blocking code from running and to ensure the correct sequence of events. It’s even a great way to log something in the console to confirm when it finally does get called as part of troubleshooting. The callback function is put into the callback queue while the currently running functions are completed, then after the call stack is cleared, the communication to the DOM or server can happen for the processed function, and then the event loop will grab the remaining callback functions in the queue and add them into the call stack.

It’s important to consider how the execution sequence is impacted when using asynchronous callbacks, because one function has to wait for another function before it’s called, otherwise you could cause a blockage. Asynchronous functionality is one reason why Javascript’s is able to be responsive and can often deliver fast results when code is written properly. You can ensure some functions occur before others as you develop your code to avoid the program from getting stuck working on just one function before it can even touch any others, otherwise you could create a poor user experience with slow or broken functionality. Exploring more advanced concepts such as setTimeout, using Event Listeners, and handling Promises can help further improve your code.

Asynchronous Callback Example:

btn.addEventListener('click', () => {
alert('You clicked me!');
let pElem = document.createElement('p');
pElem.textContent = 'This is a newly-added paragraph.';
document.body.appendChild(pElem);
});
// developer.mozilla.org: Async callbacks

The btn.addEventListener() function above takes in the event type ‘click’ that it is listening for, then a callback function as its second parameter. It performs the corresponding action of displaying the alert box and text on the DOM as well as creating and appending the new p elements and text. These actions do not occur immediately, but only happen when the callback gets invoked by clicking the button on the page.

Callback Function Hell: a.k.a. the ‘Pyramid of Doom’

Callbacks had been an early way to create asynchronous javascript functions. They are great for limited situations where you need to run code without causing a blockage and then return the value needed when the callbacks have also run. There are some drawbacks to overusing them however. It’s possible in some situations one callback could be nested into another and that may be a bit awkward, but it would still work. The trouble starts when you start nesting too many callbacks into one structure because it soon becomes a real mess to read and it’s more difficult to manage. The wedge shape below is a good indicator that you’ve relied too heavily on the callback function.

Press enter or click to view image in full size
https://dev.to/koladev/a-simple-guide-to-asynchronous-javascript-callbacks-promises-async-await-4m03

Re-calling What I’ve Learned

I’ve learned how callbacks are a great way to organize the sequence of events, and help streamline functionality. They can have a function wait for the completion of other resource intensive actions like downloading things, reading files, or talking to databases. In my own life I can see how this type of asynchronous organization is more natural and it makes a lot more sense when I write my code. As an example, when I call ahead to a restaurant for my to-go order and then let them cook it and wait for the confirmation email for my pickup time before I take the action to go to pick it up I end up with hot food out of the kitchen as soon as I arrive, but if I just went straight to the restaurant as soon as I was hungry and then ordered I would have to sit down and wait for the food to be made before it can even be served. I found callbacks to be a good introduction to asynchronous functionality and I’m excited to explore more about other advanced functions.

Thanks for reading my blog!

--

--