Callback Functions

Program demonstrating callback functions

IntermediateTopic: Function Programs
Back

JavaScript Callback Functions Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Callback: Function passed as argument to another function

// Example 1: Simple callback
function greet(name, callback) {
    console.log("Hello, " + name);
    callback();
}

greet("John", function() {
    console.log("Callback executed!");
});

// Example 2: Callback with parameters
function processArray(arr, callback) {
    let result = [];
    for (let item of arr) {
        result.push(callback(item));
    }
    return result;
}

let numbers = [1, 2, 3, 4, 5];
let doubled = processArray(numbers, function(num) {
    return num * 2;
});

console.log("\nDoubled:", doubled);

// Example 3: Using arrow functions
let squared = processArray(numbers, num => num ** 2);
console.log("Squared:", squared);

// Example 4: setTimeout callback
console.log("\nStart");
setTimeout(function() {
    console.log("This runs after 1 second");
}, 1000);
console.log("End");

// Example 5: Array methods with callbacks
let arr = [1, 2, 3, 4, 5];

// forEach
arr.forEach(function(num) {
    console.log("Number:", num);
});

// map
let doubled2 = arr.map(num => num * 2);
console.log("\nMapped:", doubled2);

// filter
let evens = arr.filter(num => num % 2 === 0);
console.log("Filtered:", evens);

// Example 6: Custom callback with error handling
function fetchData(successCallback, errorCallback) {
    let success = true; // Simulate API call
    
    if (success) {
        successCallback({ data: "Success!" });
    } else {
        errorCallback("Error occurred");
    }
}

fetchData(
    function(data) {
        console.log("\nSuccess:", data);
    },
    function(error) {
        console.log("Error:", error);
    }
);
Output
Hello, John
Callback executed!

Doubled: [ 2, 4, 6, 8, 10 ]

Squared: [ 1, 4, 9, 16, 25 ]

Start
End
This runs after 1 second
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Mapped: [ 2, 4, 6, 8, 10 ]

Filtered: [ 2, 4 ]

Success: { data: 'Success!' }

Understanding Callback Functions

This program demonstrates callback functions in JavaScript.

Callback Function Definition

A callback is a function passed as an argument to another function, to be executed later.

Example 1: Simple Callback

Basic callback pattern:

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

Example 2: Callback with Parameters

Pass data to callback:

function processArray(arr, callback) {
    for (let item of arr) {
        callback(item); // Pass item to callback
    }
}

Example 3: Arrow Function Callbacks

Modern syntax:

arr.map(num => num * 2);

Example 4: Asynchronous Callbacks

Used with async operations:

setTimeout(function() {
    console.log("Delayed execution");
}, 1000);

Example 5: Array Method Callbacks

Built-in array methods use callbacks:

forEach(): Iterate
map(): Transform
filter(): Select
reduce(): Accumulate

Example 6: Error Handling Callbacks

Common pattern:

function fetchData(success, error) {
    if (success) {
        success(data);
    } else {
        error(message);
    }
}

When to Use:

Event handlers
Array operations
Asynchronous operations
API calls
Custom iteration

Callback Hell Problem:

Nested callbacks become hard to read:

func1(function() {
    func2(function() {
        func3(function() {
        });
    });
});
            // Hard to read!

Solutions:

Promises
Async/await
Named functions instead of anonymous

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Callback Functions

This JavaScript program is part of the "Function Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents