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 : 5910  
 
Silvia Mazzetta

Silvia Mazzetta

Web Developer, Blogger, Creative Thinker, Social media enthusiast, Italian expat in Spain, mom of little 7 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

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration