Trusted answers to developer questions

What are callbacks in JavaScript?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Passing function as an argument

Just like almost everything in JavaScript (except primitive data types), functions are an object type. So like any other object types, functions can be passed to other functions.

When a function is passed as an argument, it is called a callback function. This callback function can be invoked inside the function calling it at any point, especially when some routine or action has been completed.

svg viewer

Since JavaScript is an event-driven language, you can’t just call one function after another and hope both of the functions will execute in the right order.

Instead of waiting for a response, JavaScript keeps on executing, while listening for events in the background. This is where callbacks prove to be really beneficial since they can be called from inside the called function when the time is right e.g. to return some kind of useful data.


Example

Have a look at the code given below.

Console

This is how it’s working:

  • Lines 1-9: The calculateSum function receives a number n, and a callback function. It sums the numbers from 1 up to n, prints out the calculated sum and passes it to the callback function, as shown on Line 8.

  • Lines 12-14: When calling the calculateSum function, the callback function has also been defined inside the function call. It takes the sum passed to it by calculateSum and uses that sum to print out the average.

The callback function can also be defined separately and then passed to the function call.

RELATED TAGS

callback
js
eventloop
asynchronous
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?