Categories
javascript Uncategorized

JavaScript Fundamentals: Callback Functions

JavaScript Fundamentals: Callback Functions

What Is A Callback Function?

Callback functions are functions that are passed as arguments into other functions.

The functions that receive these callback functions are arguments are known as higher-order functions.

Callback functions help to create asynchronous or asynch code. In other words, callback functions create staggered timing for the execution of a particular calculation, breaking away from the default execution of code in JavaScript which reads code from top to bottom, one code block after another.

Here is an excerpt from a helpful resource:

In its most basic form, JavaScript is a synchronous, blocking, single-threaded language, in which only one operation can be in progress at a time. But web browsers define functions and APIs that allow us to register functions that should not be executed synchronously, and should instead be invoked asynchronously when some kind of event occurs (the passage of time, the user’s interaction with the mouse, or the arrival of data over the network, for example). This means that you can let your code do several things at the same time without stopping or blocking your main thread.


Whether we want to run code synchronously or asynchronously will depend on what we’re trying to do.


There are times when we want things to load and happen right away. For example when applying some user-defined styles to a webpage you’ll want the styles to be applied as soon as possible.


If we’re running an operation that takes time however, like querying a database and using the results to populate templates, it is better to push this off the main thread and complete the task asynchronously. Over time, you’ll learn when it makes more sense to choose an asynchronous technique over a synchronous one.

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#:~:text=Async%20callbacks%20are%20functions%20that,something%20of%20interest%20has%20happened

Callback functions exist within many different contexts but, to better understand their flexibility, I have, below, outlined a few instances in which they can appear.

Callback functions, like all functions, can be named whatever you want or, in ES6 shorthand, may not even be named at all and only implied by a set of arguments.

In the examples below, I mark where the callback functions fall in the syntax by simply naming them “callback” so the syntax is clear.

Example: Callback Function in DOM

A common scenario where a callback function might be seen is when using DOM methods such as addEventListener in Example 1, below.

function callback(){
   // do something that will be triggered by an onClick event listener. 
}
window.addEventListener('onClick', callback);

Because callback functions are passed along as arguments to the higher-order function, we omit the ( ) when we initially invoke them because otherwise they would be executed immediately, as a regular function. Omitting the ( ) indicates it is to be passed along as an argument and executed at a later point in the process.

Example: Callback Function in an Array Method

Let’s try another example. Here we have an array of two objects called students. We want to find the total age of all the students.

(To learn more about the reduce() method, visit this post. )

In this example below, the callback function takes two arguments: the accumulator and the currentValue representing an element of the array that is currently being iterated over.

const students = [
  {
     age: 2,
     name: "Mikey",
  },
  {
     age: 6,
     name: "Susie",
  }
];

let totalAge = students.reduce(getTotalAge, 0);

// below, student holds a value of the object received from the looped array element
function getTotalAge(accumulator, student){ 
    return accumulator + student.age;     // add the .age from the student object to a accumulating total
}

  

Same code in shorthand ES6 with arrow functions:

let totalAge = students.reduce((accumulator, student) => accumulator + student.age);
console.log(totalAge); 

In this next example, callbackFunction is a function that operates on a delayed time schedule defined by setTimeOut, a built-in function in JavaScript.

This is an example of an asynchronous callback function, or one that operates outside of the usual flow of top-to-bottom sequential processing typical of JavaScript.

let callbackFunction = myFunction();

function myFunction(){
   console.log("this messages appears after three seconds")
}

setTimeOut(callbackFunction, 3000);  // setTimeOut calls the callbackFunction after 3000 milliseconds.
LeaNakamura's avatar

By LeaNakamura

I'm a Brooklyn-based web development student, musician and textile artist originally from Maui, Hawaii.

Leave a comment

Design a site like this with WordPress.com
Get started