DEV Community

Salvietta150x40
Salvietta150x40

Posted on • Originally published at ma-no.org

Javascript: What are Callbacks and how to use them

What are Callbacks and how to use them

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();
}

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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);
} 
}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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

  1

  2

  3

  4

  8

  9

  5

  6

  7

Enter fullscreen mode Exit fullscreen mode

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);

});
Enter fullscreen mode Exit fullscreen mode

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

  1

  2

  4

  8

  9
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)