Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

Callbacks in JavaScript

A callback is a function that is passed as an argument to another function and is executed later when a particular task is completed.

What is a Callback?

In JavaScript, a callback function is a function that is passed to another function as an argument. The receiving function can execute the callback when it needs to perform the next action.

Simple Definition

A callback is a function passed to another function and called after a task is completed.

How a Callback Works
Main Function
→
Callback Function
→
Result

The main function receives a callback and executes it when required.

Example 1: Simple Callback

A callback can be passed to another function and executed from inside that function.

function greet(callback) {

    callback();

}

function showMessage() {

    console.log("Welcome to JavaScript!");

}

greet(showMessage);
Welcome to JavaScript!

Example 2: Callback with Parameters

A callback can also receive data from the function that calls it.

function getStudent(callback) {

    const name = "Rahul";

    callback(name);

}

getStudent(function(name) {

    console.log("Student Name:", name);

});
Student Name: Rahul

Example 3: Callback after a Task

Callbacks are commonly used when a task needs to be completed before another function runs.

function completeTask(callback) {

    console.log("Task completed.");

    callback();

}

completeTask(function() {

    console.log("Callback executed.");

});
Task completed.
Callback executed.

Example 4: Callback with Data

A callback can be used to execute a function after data is prepared or a task is completed.

function getData(callback) {

    var data = "Data received";

    callback(data);

}

getData(function(result) {

    console.log("Callback executed successfully.");
    console.log(result);

});
Callback executed successfully.
Data received

Why Use Callbacks?

Important Benefits

• Execute one function after another task.

• Pass functions as values.

• Handle asynchronous operations.

• Useful for timers and API operations.

• Callbacks are an important foundation for asynchronous JavaScript.

Summary

A callback is a function passed to another function as an argument. The receiving function can execute the callback when the required task is completed. Callbacks are widely used in JavaScript, especially for asynchronous operations.