Callback Functions

Program demonstrating callback functions

JavaScriptIntermediate
JavaScript
// 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!' }

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:

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

Example 2: Callback with Parameters

Pass data to callback:

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

Example 3: Arrow Function Callbacks

Modern syntax:

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

Example 4: Asynchronous Callbacks

Used with async operations:

javascript
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:

javascript
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:

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

Solutions:

  • Promises
  • Async/await
  • Named functions instead of anonymous