What is a Callback Function in JavaScript? | Simplilearn

A JavaScript callback is a function which is to be executed after another function has finished execution.

A more formal definition would be – Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTME

Enroll NowPost Graduate Program: Full Stack Web Development

Need of Callback Functions

We need callback functions because many JavaScript actions are asynchronous, which means they don’t really stop the program (or a function) from running until they’re completed, as you’re probably used to. Instead, it will execute in the background while the rest of the code runs.

Let us look at a real world example to understand it (synchronous callback function) better.

A callback’s primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to “execute this code every time the user clicks a key on the keyboard.”

const button = document.getElementById(‘button’);
function callback(){
console.log(“Hello world”);
}

button.addEventListener(‘click’,callback);

In the above code, we add addEventListener as a function and we are passing another function callback as an argument. And when a click event is triggered the addEventListener registers the callback function.

Callback_functions_in_JavaScript_1

One More Example! (Asynchronous Callback Function)

If you wanted to download data from a server (which may take long durations of time), it would be wasteful for your program or function to just freeze while you waited for the data to be fetched. Instead, it’s common practice to execute the fetching operation in the background.

This implies that if you have two functions in a row, one of which is asynchronous, function B will be performed while the other is still running. If function B is dependent on the data that function A is retrieving, you will run into issues.

async function fetchUsers() {
  const resp = await fetch(‘<https://jsonplaceholder.typicode.com/users>’);
  const users = await resp.json();
  const names = users.map(({ login }) => login);
  console.log(names);
}

An async keyword is placed as a prefix to the function to make a function asynchronous.

The above function fetches fake user data of 10 users. We are then converting it to a json object to extract the user data.

The asynchronous functions return a promise, when the asynchronous function encounters the term await <promise> (notice that fetch() delivers a promise), it stops its execution until the promise is resolved. To read more about promises click here.

An asynchronous callback function differs from an asynchronous function. The higher-order function executes the asynchronous callback function in a non-blocking way. However, while waiting for promises (await promise>) to resolve, the asynchronous function stops its execution.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarth

EXPLORE COURSEFull Stack Java Developer Course

We can make this an asynchronous callback by adding it to an event, like a button click.

const button = document.getElementById(‘fetchusers’);

button.addEventListeners(‘click’, fetchUsers);

Callback_functions_in_JavaScript_2.

Nesting Callbacks and Callback Hell

There are many ways to handle nested callbacks, using async await as discussed above, or using the old school way of promises (read about promises) or splitting the code into different functions.

Using Promises

We must generate a new promise for each callback in order to convert them to promises. When the callback is successful, we may resolve the promise. If the callback fails, we can reject the promise.

function getUserPromise {
  const newUser = getUserFromApi(user)

  return new Promise((resolve, reject) => {
    if (user) {
      resolve(user)
    } else {
      reject(new Error(‘No more new users!’))
    }
  })
}

Now you can create one more function and call the above function as a callback.

Free Course: JavaScript for Beginners

Learn the Basics of JavaScript

Enroll NowFree Course: JavaScript for Beginners

Using async-await

We have already seen how to create an asynchronous callback in the above section.

We can write asynchronous functions as if they are synchronous (executed sequentially) with the use of await as it stops the execution until the promise is resolved (function execution is successful).

const userProfile = async () => {
  const user = await fetchUsers(1) // argument indicated number of users to fetch
  const updatedAddress = await updateAddress(user)
  const pincode = await getPincode()
  const updateUser = await updateUser(user, updatedAdress, pincode)
  return user
}

// fetch and update user profile
userProfile()

You can nest these functions in promises as well.

We offer complete Job Guarantee and money-back if you don’t secure a job within 6 months of graduation. Get interview ready with intense and comprehensive career mentoring sessions in our Full Stack Java Developer Program. Enroll TODAY!

Conclusion

We have looked at the what and why’s of callback functions in JavaScript, along with examples using synchronous and asynchronous functions to understand callbacks.

In the end we also covered what is nested callbacks and how to tackle them using promises and async-await.

To learn more about JavaScript and its amazing features which powers the websites, take the Full-Stack Web Development  course.

You can also sign up on our SkillUp platform to improve your software development knowledge. It is a Simplilearn initiative that offers free online courses to help you hone your skills in multiple programming languages, including JavaScript.