Javascript: what are callbacks and how to use them.

by Silvia Mazzetta Date: 23-10-2020 javascript coding functions callbacks

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is the use of Callbacks.

 

What is a Callback?

 

Simplifying, it is to pass a function as a parameter so that this function runs our parameter. You may have already done it in C#, PHP or Java: make your function/method return something to perform the action.This is what we usually do as programmers.

In the following example, the function foo receives by parameter another function, which is the callback. The function foo is in responsible of executing the callback.

 
function foo(callback) { 
 //do something
  callback();
}
 

It is important to take into account that when we pass a callback we only pass the definition of the function and do not execute it in the parameter.

So, the container function chooses when to execute the callback.

A very common example of callback is as a listening function of an event.

 
function showAlert(){
   alert('Alerta');
}  
button.addEventListener('click', showAlert);
 

In this example, showAlert is a callback. We can also write the callback as an anonymous function:

 
button.addEventListener('click', function(){
  alert('Alerta');
});


Callbacks are also used to "warn" when a function has finished doing something:

 

function foo(callback) {
   console.log("hello")
   callback();
}foo(function(){console.log("finished")});
→ hello
  finished
 

The use of callback is also known as callback pattern, since it is essentially a pattern as it is a solution to common problems. In addition, the use of callbacks is related to functional programming, which specifies the use of functions as arguments.

Callbacks can help not to repeat code and its maintenance, to get more specific functions and, in some cases, to improve the level of abstraction and code reading.

 

Checking the asynchronous execution with callbacks

 

The callbacks themselves are synchronous. In the following example, it is the container function that chooses when the callback is executed, and it is executed without causing another execution flow.

 
function foo(val, callback){
 if(val == 1){
  callback(true);
}
 else{
  callback(false);
} 
}
 

Therefore, callbacks are very useful for handling asynchrony in JS. For example, they can be very useful when we are testing asynchronous elements.

Let's see an example.

Within a test, we create a setTimeOut (asynchronous method since it causes another execution flow). The test can work incorrectly because it does not wait for the asynchronous operation to be finished and it does not get executed.

To make sure that the content of the setTimeOut is always executed, we pass a callback to it. Until the callback has been called, JS will not leave the test (i.e. the function).

 
it("checks something of the DOM", function (done) {
foo1();
foo2();
foo3();
function onTimeout() {
  expect(parseInt(element.innerHTML)).toEqual(x);
done();
}
setTimeout(onTimeout, 1000);
});
 

Let's see what the order of execution is:

 
it("restart the counter time", function (done) {
  console.log(1);
  foo1();
  console.log(2);
  foo2();
  console.log(3);
  foo3();
  console.log(4);
function onTimeout() {
console.log(5);
expect(parseInt(element.innerHTML)).toEqual(x);
console.log(6);
 done();
console.log(7);
}
console.log(8);
setTimeout(onTimeout, 1000);
console.log(9);
});


El orden de ejecución, al pasar el test, es el siguiente:

 
  1

  2

  3

  4

  8

  9

  5

  6

  7


With the done parameter we make sure that the number 5, 6 and 7 are always executed.
Let's see the case where we don't pass callback to the test:

it("restart the counter time", function () {
  console.log(1);
  foo1();
  console.log(2);
  foo2();
  console.log(3);
  foo3();
  console.log(4);
function onTimeout() {
console.log(5);
expect(parseInt(element.innerHTML)).toEqual(x);
console.log(6);
}
console.log(8);
setTimeout(onTimeout, 1000);
console.log(9);

});

The order of execution, when passing the test, is as follows:

  
  1

  2

  4

  8

  9
 

Neither the 5th nor the 6th is ever executed.

Callbacks to eliminate knowledge on the dependencies

In a code, it is usual that there are functions that depend on other functions. When many parts of our code depend on other parts, it is easier for some methods to affect others without us having foreseen it or for any future change to be complex and laborious. In general, the less dependency, the better.

There are several ways to eliminate dependency and one of them is the use of callbacks. This is not a common solution nor can we use it in every situation, but it can help us in certain cases.

Through callbacks, we can reverse the dependency at the knowledge level and make one function unaware of the other function it is executing.


Let's look at an example with a countdown:

 
var seconds = 20;function startCountDown(){
  setInterval(function(){
    seconds--;
    showSeconds();
  }, 1000);
}function showSeconds(){
   console.log(seconds);
}startCountDown()
 

The startCountDown function depends on the showSeconds() function. Every second, startCountDown executes the showSeconds function. If we want to minimize this dependency, we can make the startCountDown function unaware of the showSeconds function by passing it a callback.

 
var seconds = 20;function startCountDown(onTimeChanged){
  setInterval(function(){
    seconds--;
    onTimeChanged();
  }, 1000);
}function showSeconds(){
  console.log(seconds);
}startCountDown(showSeconds);

 
by Silvia Mazzetta Date: 23-10-2020 javascript coding functions callbacks hits : 7529  
 
Silvia Mazzetta

Silvia Mazzetta

Web Developer, Blogger, Creative Thinker, Social media enthusiast, Italian expat in Spain, mom of little 9 years old geek, founder of  @manoweb. A strong conceptual and creative thinker who has a keen interest in all things relate to the Internet. A technically savvy web developer, who has multiple  years of website design expertise behind her.  She turns conceptual ideas into highly creative visual digital products. 

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

Clicky