How callback function work in Javascript?
Photo by Michael Dziedzic on Unsplash edited by Author

How callback function work in Javascript?

What is a callback function in javascript?

--

What is a callback function?

A callback function is a function that you provide to another function as a parameter. The other function can utilize your function whenever necessary and may even return something to you. This allows for collaboration and the ability to perform tasks together with other functions.[ref]

It is evident that at least two functions are required for a callback function to work.

Let’s consider an example

Imagine you are working as a developer at XYZ company. The manager asks you to write a code that calculates and displays the total salary of the company’s employees. How would you approach writing this code?

You could simply calculate and display the output like this:

// Calculate the salary
let a = 3000;
let b = 3600;
let c = 2500;
let d = 6000;
console.log(a + b + c + d);
// Output => 15100

That seems quite easy, a piece of cake I would say, but that’s not a callback function. Coding is not always that simple. Often, you have to solve complex problems, requiring you to write complex code.
Let’s make it more complicated.
Please understand that there are other methods to achieve this output, but here we are going to explore the concept of a callback function in JavaScript.

Again, I am not performing this calculation to determine the sum of four values. Instead, I am calculating the sum of four values to gain a better understanding of how callback functions work in JavaScript.

I promise to do my best to help you understand this concept. So, stay with me.

How does a callback function work in JavaScript?

Firstly, we will create a function called “payout”:

// Function to display salary
function payout(payment, callback) {
let salary = payment.A + payment.B + payment.C + payment.D;
callback(salary);
}

The “payout” function has two parameters: “payment” and “callback.” You can name them according to your project’s needs, but here I prefer “payment” and “callback.”
Inside the function, I have declared a variable called “salary,” which calculates the sum of the four values (A, B, C, and D) that we will define later.
In addition, I am trying to call a function “callback(salary),” but I have not yet defined any callback function. Also, I have not assigned any values to A, B, C, and D.
I have two things to do: declare a callback function and assign values to A, B, C, and D.

Let’s first declare the callback function:

// Define the callback function
function displaySalary(salary) {
console.log("Salary:", `${salary}$`);
}

Now let’s analyze the above code.
There is a function called “displaySalary” with a parameter named “salary.” The purpose of this function is to print the salary in the console. Here, “salary” is a variable that will receive its value from the sum of A, B, C, and D.
Now, let’s assign values to A, B, C, and D:

// Payment details
let payment = {
A: 3000,
B: 3600,
C: 2500,
D: 6000
};

Everything looks good so far. Now, let’s try to call the function.
Here’s the function call:

// Call the payout function and pass the payment details and callback function
payout(payment, displaySalary);
// output => Salary: 15100$

How does this code provide the correct output?
Let’s revisit the second function that we declared earlier:

// Define the callback function
function displaySalary(salary) {
console.log("Salary:", `${salary}$`);
}

I declared a function called “displaySalary” with a parameter named “salary.” This parameter receives its value from the “salary” variable that I declared in the “payout” function. However, since no value is assigned yet,

the function will try to find the values within its own function scope. If they are not found there, JavaScript will look for the values in the global scope (if you are unfamiliar with global variables, you can refer to my previous article).

In the global scope, there is a variable named “payment” (but we are looking for “salary”) that is an object containing the values of A, B, C, and D.
So, the value of “salary” will be equal to 3000 + 3600 + 2500 + 6000 = 15100.

let salary = payment.A + payment.B + payment.C + payment.D

Now that we have the value of “salary,” let’s return to our second function.
Here, I called the “payout” function that I initially declared in my code.

// Call the payout function and pass the payment details and callback function
payout(payment, displaySalary);
// output => Salary: 15100$

Here’s how the code works:

payout(payment, displaySalary);

Argument 1: payment = salary = 15100
Argument 2: displaySalary = console.log(“Salary:”, `${salary}$`) // I am using backticks here to add “$” after the value.
Therefore, the output will be:
Salary: 15100$

How callback function work in Javascript?
Image by Author

Here is the full code:

// Function to display salary
function payout(payment, callback) {
let salary = payment.A + payment.B + payment.C + payment.D;
callback(salary);
}
// Define the callback function
function displaySalary(salary) {
console.log("Salary:", `${salary}$`);
}
// Payment details
let payment = {
A: 3000,
B: 3600,
C: 2500,
D: 6000
};
// Call the payout function and pass the payment details and callback function
payout(payment, displaySalary);
// output => Salary: 15100$

Another Example

Now, I hope you have a clear understanding of how callback functions work. If not, then it’s my fault! :)

However, let’s set that aside for a moment and explore another example that involves the `setTimeout` function, which is a bit more complex than the previous one.

The `setTimeout` function allows us to schedule the execution of a callback function after a specified delay in milliseconds. Let’s say we want to write a function that greets someone after a delay of 3 seconds. We can achieve this by utilizing a callback function and the `setTimeout` function in the following way:

function greet(name, callback) {
// This function takes a name and a callback as parameters
console.log("Hello, " + name + "!");
// This function schedules the execution of the callback after a 5-minute delay
// 300000 ms = (300000/1000)/60 = 5 min
setTimeout(callback, 300000);
}

function bye() {
// This is the callback function that will be executed after 5 minutes
console.log("Goodbye!");
}

greet("John", bye);
// This calls the greet function with "John" and bye as arguments

// The output will look something like this:
// Hello, John!
// (after 5 minutes)
// Goodbye!

In the example above, we define a ‘greet’ function that takes a ‘name’ and a ‘callback’ as parameters. Inside the ‘greet’ function, we first greet the person by printing “Hello, [name]!” to the console. Then, using the ‘setTimeout’ function, we schedule the execution of the ‘callback’ function after a 5-minute delay.

We also define a ‘bye’ function as the callback, which simply logs “Goodbye!” to the console. When we call the ‘greet’ function with the name “John” and the ‘bye’ function as the callback, the output will display the initial greeting followed by the farewell message after the specified delay.

The bottom line

Callback functions in JavaScript provide a powerful mechanism for collaboration and coordination between functions. By passing a callback function as a parameter to another function, we enable the flexibility to execute specific actions at specific times or in response to certain events. The callback function can be invoked by the receiving function, allowing for the seamless exchange of data and the ability to perform tasks in a coordinated manner. Understanding how callback functions work in JavaScript and using it effectively can greatly enhance the efficiency of our code, enabling us to solve complex problems and create more dynamic and interactive applications.

--

--