Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Examples of callback functions and methods
3.
Callbacks in a callback
4.
Error handling
5.
Callback hell or Pyramid of Doom
6.
Frequently Asked Questions
7.
Key takeaways
Last Updated: Mar 27, 2024

Callbacks in Javascript

Author Reet Maggo
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Callbacks, usually used for asynchronous actions, are functions passed into some other functions as arguments to be executed later (as required by asynchronous actions). Some JavaScript functions that let us schedule asynchronous actions are setTimeout, loadScript, etc. We will be discussing the loadScript function as an example to explain the need for callbacks.

Callbacks provide a sequence control over the code such that users have more control when implementing and executing the functions. The need for repeatedly creating functions for every time similar tasks need to be performed is eliminated. 

Examples of callback functions and methods

loadScript() loads scripts and modules in Js when given a script (which will be ‘scr1’ in our case). loadScript() will create a script tag, append it to the page. Loading scripts is an asynchronous action. Hence it will start loading first but will be executed by the browser only when complete, by which the function will already be finished.

function loadScript(scr1)
{
  let script = document.createElement('script');
  script.scr1 = scr1;
  document.head.append(script);
}

 

The function can be used as loadScript(...). Since the execution will happen after the function finishes, any code below loadScript() will not wait for the script loading to finish. This means that declaring and running new functions below would not be possible

loadScript('/my/script.js');

 

It would be helpful to find out when the script finally runs to use new variables and functions from the script. Therefore, we will add a callback function as an argument to loadScript(), which will execute when the script will load. To call new functions from the script, we will now write those in the callback itself.

function loadScript(scr1, callback)
{
  let script = document.createElement('script');
  script.scr1 = scr1;
  script.onload = () => callback(script);
  document.head.append(script);
}

 

Adding a new function in the callback itself:

loadScript('/my/script.js', function()
{
  newFunction();
  ...
});

 

When to actually use callbacks?

Callbacks are usually preferred to be used in asynchronous actions where functions do not have to wait for one task to be over before proceeding to the next one. One such asynchronous Javascript function where callbacks can be used is setTimeout(), among many others.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Callbacks in a callback

If we wish to add two functions, one after the other, we will put the second loadScript() inside the callback function.

loadScript('/my/script.js', function(script)
{
  alert(`${script.src} loaded. Loading the next one`);
  loadScript('/my/script2.js', function(script)
  {
    alert(`Second script loaded`);
  });
});

 

We could further nest each loadScript in the previous loadScript function, and every action will be inside a callback this way. However, you must have already noticed how complicated this could get if the number of actions is increased. Further nesting will only make the code deeper and harder to understand or manage.

Error handling

Errors in callbacks are usually handled as arguments of the callback function. The first argument is generally named error in the function, so the callback is called with the first argument if an asynchronous function goes wrong.

In the example we used, callback(null, script) will be called if the loading is successful. In case it fails, callback(error) will be called.

loadScript('/my/script.js', function(error, script)
{
  if (error)
  { }
  else
  { }
});

 

Callback hell or Pyramid of Doom

As observed above, multiple asynchronous actions following nested loops within nested loops make it very difficult to manage the code.“Callbacks in callbacks” hence prove to be a bad idea for bigger codes.  The code becomes even deeper with more complications such as conditional statements, loops, etc. This is called “Callback Hell.” Instead of nesting, we will make every action a top-level standalone function so that the code is not too deep to manage.

loadScript('first.js', step1);
function step1(error, script)
{
  if (error)
  {
    handleError(error);
  }
  else
  {
    loadScript('second.js', step2);
  }
}

function step2(error, script)
{
  if (error)
  {
    handleError(error);
  } 
  else
  {
    loadScript('third.js', step3);
  }
}

function step3(error, script)
{
  if (error)
  {
    handleError(error);
  }
  else
  {  }
}


You can compile with the help of Online Javascript Compiler for better understanding.

Frequently Asked Questions

Q1. What is an error-first callback in Js?

Ans. It is a function returning either successful data or an error object. In error-first callbacks, the first argument is for the error object, and the argument returns any error that takes place.

Q2. Why do we use callbacks?

Ans. Callbacks are functions inside functions that are used to handle asynchronous actions, i.e., they help us execute a function right after another function has been returned.

Q3. Are callbacks asynchronous?

Ans. Callbacks are functions passed as arguments to some other function. They do not have any special syntax, and the function that takes them as arguments is called a higher-order function. Callback functions aren't necessarily asynchronous in nature, but they can and, in fact, prefer to handle asynchronous operations.

Key takeaways

We learned about callback functions and methods, callbacks inside callbacks, error handling, and efficiently solving complex code issues caused by nesting in callback functions. The examples used aim to provide a better understanding of the concept altogether.

You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.

Live masterclass