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

Silvia Mazzetta

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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…

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