Priyanka Rote

JavaScript Callback Function

What is a callback function?

“A callback is a function that is passed as an argument to another function”

Which is then invoked inside the outer function to complete some kind of routine or action. 

Callbacks are also known as a higher-order function.

Syntax:-

we can also pass functions as parameters to other functions and call them inside the outer functions. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function. But that’s not all.

Example:-

Output:-

Hi Peter

I am callback function

Why do we need Callback Functions?

JavaScript runs code sequentially in top-down order. However, there are some cases where code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has been completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then call it back right after something has happened or some task is completed. 

What is a Callback Advantage?

Callbacks can help to make your code more maintainable if you use them well. They will also help us to:

Keep your code DRY (Do Not Repeat Yourself)

Implement better abstraction where you can have more generic functions like compute that can handle all sorts of functionalities (e.g., sum, product)

Improve code readability and maintainability.

So far, we have only seen callbacks that are executed immediately; however, most of the callbacks in JavaScript are tied to an event like a timer, API request, or reading a file.

How to create a Callback?

To understand what I’ve explained above, let me start with a simple example. We want to log a message to the console but it should be there after 3 seconds.

Example:-

There is a built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds). So here, the “message” function is being called after 3 seconds have passed. (1 second = 1000 milliseconds)

In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.

What are Asynchronous callbacks?

An asynchronous callback is a function that is passed as an argument to another function and gets invoked zero or multiple times after certain events happen.

It’s like when your friends tell you to call them back when you arrive at the restaurant. You coming to the restaurant is the “event” that triggers the callback. Something similar happens in the programming world. The event could be you click a button, a file is loaded into memory, and request to a server API, and so on.

Example :-

First, you notice that we are using anonymous functions (in the previous example, we were passing the named functions such as sum and product). The callback passed to setInterval is triggered every second, and it prints tick. The second callback is called one after 5 seconds. It cancels the interval, so it just writes tick five times.

Callbacks are a way to make sure a particular code doesn’t execute until another has already finished.

The console.log(‘tick’) only gets executed when a second has passed.

The functions setInterval and setTimeout callbacks are very simple. They don’t provide any parameters on the callback functions. But, if we are reading from the file system or network, we can get the response as a callback parameter.

 

 

Callback as an Arrow Function

If you prefer, you can also write the same callback function as an ES6 arrow function, which is a newer type of function in JavaScript:

Example :-

Benefit of Callback function

The benefit of using a callback function is that we can wait for the result of a previous function to call and then execute another function call.

In this example, we are going to use the setTimeout( ) method to mimic the program that takes time to execute, such as data coming from the server.

Example :-

Output:-

Hello John

Hello world 

Share