Callbacks in JavaScript

What is a callback?

by Janeth Kent Date: 19-12-2022 javascript


Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function.

The function that receives the callback as an argument is called a higher-order function.

Any function can be used as a callback, since it is sufficient to pass it to another function as a parameter.

Callback functions are not asynchronous by nature, but they are often used for that purpose, for example when they are passed as arguments to the different events accepted by the browser APIs, allowing JavaScript to interact with the DOM of a page or with the system.

How to create a callback

To create a callback you simply declare a function, pass it to another function as a parameter and execute it inside that function. Below is an example of a callback.

 
// Our function
function HiWorld() {
console.log('Hi World!');
}
// Function that accepts another function as a parameter
function talK(callback) {
callback(); // This call is called a callback
}
// We pass one function to another
talK(HiWorld);
 

What we have done in the example is to define the HiWorld() function and the talK function, which accepts another function as an argument. We then executed the function talK to which we passed the function HiWorld() as a parameter.

On executing the above code we will obtain this output:

 
Hi World!
 

Asynchronism with callbacks

JavaScript is not an asynchronous language by nature. However, JavaScript callbacks are often used to create asynchronous code when used with the APIs of the JavaScript runtime environment, either a browser or the Node.js environment.

For example, you can pass a function as a callback to browser events, such as onClick , onMouseOver or onChange events.

You won't know when a user will click a button, but you can create a handler that handles the event when it happens. The handler accepts a function as a callback, which will be executed when the event is triggered:

 
document.getElementById('#btn').addEventListener('click', () => {    
console.log('The button has been clicked');  });



It is also very common to add code to the load event of the browser's window object, which will execute the callback function we define when the page has loaded and the DOM is ready:

 
window.addEventListener('load', () => {    
console.log('Page loaded'); 
});
 

We don't only use callbacks to handle browser DOM events, as another very common use of callback functions is in setTimeout events, which allow us to execute the function we pass as a parameter when the time we define in milliseconds elapses:

 
setTimeout(() => {    
console.log('It's been a second');  
}, 1000);
 

Over time, the simple HTML pages of the 1990s have evolved into dynamic applications that run in your browser. Applications often make requests to APIs located on different servers. The most common nowadays is that these requests are executed asynchronously, transparently to the user, as in the case of XHR requests, which accept a callback function as a parameter.

In the following example we assign a function to the onreadystatechange property of an XMLHttpRequest object . The function we assign will be executed as a callback when a response to the request is received:

 
const xhr = new XMLHttpRequest();    
xhr.onreadystatechange = () => {    
if (xhr.readyState === 4) {           
// We check if the request has been completed successfully.     
if (xhr.status === 200) {       
console.log(xhr.responseText);      
} else {        
// An error has occurred      
console.error('error');      
}    
}  
} 
// Iniciamos la petición
xhr.open('GET', 'https://api.tld/endpoint');  
xhr.send();
 

If we didn't use an asynchronous function, the browser would have to keep checking if a response has been received, blocking the execution of the JavaScript code in the browser, since JavaScript is a synchronous, single-threaded language by nature.

We also use callbacks when using the JavaScript fetch API, which is one of the best ways to make asynchronous requests.

Error handling in callbacks

There are several strategies for handling callback errors when callbacks are executed asynchronously. For example, the most common in the Node.js environment and in the vast majority of browser APIs is for the first parameter of a callback function to be an object containing a possible error. This philosophy is often referred to as error-first callbacks.

Below you can see an example where we read a file from the system:

 
fs.readFile('/file.json', (error, data) => {    
if (error !== null) {     
// Error handling   
console.log(error);      
return;    
}    
// No error has occurred  
console.log(data);  
})
 

Common problem with callbacks

Callback functions are great for simple cases, but they are not without problems when the code gets complicated.

When we nest multiple callbacks, each one adds a level of depth to the message queue. While JavaScript can handle these situations without a problem, the code can become difficult to read. In addition, it will also be more difficult to know where an error has occurred.

Below we nest four callbacks, which is not uncommon, but you are likely to encounter much more extreme cases:

 
window.addEventListener('load', () => {    
document.getElementById('btn').addEventListener('click', () => {      
setTimeout(() => {        
items.forEach(item => {         
// Code
})      
}, 2000)    
});  
});



This situation is known as callback hell. However, we can avoid them by using the alternatives available in JavaScript.

Alternatives to callback functions

Since the ES2015 release of JavaScript, several features have been introduced that allow you to deal with asynchronous JavaScript code, avoiding callback hell. These are promises and the use of Async/Await:

- Promises: Promises in JavaScript
- Async/Await: Async/Await in JavaScript

 
by Janeth Kent Date: 19-12-2022 javascript hits : 7538  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

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…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

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…

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