DEV Community

Mahalakshmi C
Mahalakshmi C

Posted on

Callback and Closure in JavaScript

Callback functions and closures are important concepts in JavaScript. They become especially useful when working with asynchronous operations such as setTimeout().

In this blog, we will understand Callback Functions, setTimeout(), and Closures with simple examples.

Callback Function

A callback function is a function passed as an argument to another function. The receiving function can execute the callback function later when it is needed.

For example:

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function message() {
    console.log("Welcome to JavaScript");
}

greet("John", message);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello John
Welcome to JavaScript
Enter fullscreen mode Exit fullscreen mode

Here, message is passed as an argument to the greet() function. Therefore, message is called a callback function.

The important point is that we pass the function without parentheses:

greet("John", message);
Enter fullscreen mode Exit fullscreen mode

We do not write:

greet("John", message());
Enter fullscreen mode Exit fullscreen mode

because message() would execute immediately instead of being passed as a callback.

Callback with setTimeout()

setTimeout() is a JavaScript function used to execute a piece of code after a specified amount of time.

The syntax is:

setTimeout(function, delay);
Enter fullscreen mode Exit fullscreen mode

For example:

setTimeout(function() {
    console.log("Hello");
}, 2000);
Enter fullscreen mode Exit fullscreen mode

Output after approximately 2 seconds:

Hello
Enter fullscreen mode Exit fullscreen mode

Here, the function passed to setTimeout() is a callback function.

We can also write it using an arrow function:

setTimeout(() => {
    console.log("Hello after 2 seconds");
}, 2000);
Enter fullscreen mode Exit fullscreen mode

The callback is not executed immediately. It is executed after the specified delay.

Understanding Callback and setTimeout()

Consider this example:

console.log("Start");

setTimeout(() => {
    console.log("Timeout");
}, 2000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Start
End
Timeout
Enter fullscreen mode Exit fullscreen mode

Even though the setTimeout() code appears before "End", the callback executes later.

The setTimeout() callback waits for the specified delay, while JavaScript continues executing the remaining synchronous code.

Closure in JavaScript

A closure occurs when an inner function remembers and can access variables from its outer function even after the outer function has finished executing.

For example:

function outer() {
    let message = "Hello";

    function inner() {
        console.log(message);
    }

    return inner;
}

let result = outer();

result();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Here, inner() can access the message variable from outer() even after outer() has finished executing.

This is called a closure.

Closure with setTimeout()

Closures are commonly seen when using setTimeout() because the callback function can remember variables from its surrounding scope.

For example:

function greet() {
    let message = "Hello from closure";

    setTimeout(() => {
        console.log(message);
    }, 2000);
}

greet();
Enter fullscreen mode Exit fullscreen mode

Output after approximately 2 seconds:

Hello from closure
Enter fullscreen mode Exit fullscreen mode

Here, the greet() function finishes executing before the setTimeout() callback runs.

However, the callback still remembers the message variable.

This happens because the callback forms a closure over the variable message.

Callback Function vs Closure

Callback and closure are different concepts, although they can work together.

Callback Function Closure
A function passed as an argument to another function A function that remembers variables from its outer scope
Focuses on passing a function Focuses on accessing preserved variables
Commonly used with setTimeout() Can occur when an inner function accesses outer variables
Example: setTimeout(callback, 2000) Example: callback accessing name from an outer function

Callback + Closure + setTimeout()

We can combine all three concepts in one example:

function orderFood(item) {

    let message = "Your " + item + " is ready";

    setTimeout(() => {
        console.log(message);
    }, 2000);
}

orderFood("Biryani");
Enter fullscreen mode Exit fullscreen mode

Output after approximately 2 seconds:

Your Biryani is ready
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution

Let's understand the example step by step.

Step 1

The orderFood("Biryani") function is called.

item = "Biryani"
Enter fullscreen mode Exit fullscreen mode

Step 2

The message variable is created.

message = "Your Biryani is ready"
Enter fullscreen mode Exit fullscreen mode

Step 3

The callback function is passed to setTimeout().

() => {
    console.log(message);
}
Enter fullscreen mode Exit fullscreen mode

Step 4

setTimeout() schedules the callback to execute after approximately 2 seconds.

Step 5

The orderFood() function finishes executing.

Step 6

After the delay, the callback executes.

console.log(message);
Enter fullscreen mode Exit fullscreen mode

The callback still remembers the message variable because of closure.

Step 7

The output is:

Your Biryani is ready
Enter fullscreen mode Exit fullscreen mode

Conclusion

A callback function is a function passed as an argument to another function and executed when needed. setTimeout() uses a callback function to perform an operation after a specified delay. A closure allows an inner function to remember and access variables from its outer scope even after the outer function has finished executing.

Understanding callbacks, closures, and setTimeout() is important because these concepts form the foundation for understanding asynchronous JavaScript.

Top comments (0)