Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 8 · Closures and Callbacks
Interview question

What is a callback function and what are common use cases? Callback function क्या है और common use cases क्या हैं?

Answer

A callback function is a function that is passed as an argument to another function, and the receiving function will 'call back' (execute) the callback at some point during its execution.

// Simple callback example
function greet(name, callback) {
    console.log('Hello ' + name);
    callback(); // 'calling back' the callback function
}

function sayGoodbye() {
    console.log('Goodbye!');
}

greet('John', sayGoodbye);
// Output:
// Hello John
// Goodbye!

// Callback with arguments
function add(a, b, callback) {
    const result = a + b;
    callback(result); // Passing result to callback
}

add(5, 3, function(sum) {
    console.log('Sum is: ' + sum); // Sum is: 8
});

// Array methods with callbacks
const numbers = [1, 2, 3, 4, 5];

// forEach callback
numbers.forEach(function(num) {
    console.log(num * 2); // 2, 4, 6, 8, 10
});

// map callback
const doubled = numbers.map(function(num) {
    return num * 2;
}); // [2, 4, 6, 8, 10]

// filter callback
const evenNumbers = numbers.filter(function(num) {
    return num % 2 === 0; // [2, 4]
});

// Asynchronous callback - setTimeout
console.log('Start');

setTimeout(function() {
    console.log('After 2 seconds');
}, 2000);

console.log('End');
// Output:
// Start
// End
// After 2 seconds

// Reading file with callback (Node.js)
const fs = require('fs');

fs.readFile('file.txt', 'utf8', function(err, data) {
    if (err) {
        console.log('Error reading file:', err);
    } else {
        console.log('File content:', data);
    }
});

// AJAX request with callback
function fetchData(url, callback) {
    fetch(url)
        .then(response => response.json())
        .then(data => callback(data))
        .catch(error => callback(null, error));
}

fetchData('/api/users', function(data, error) {
    if (error) {
        console.log('Error:', error);
    } else {
        console.log('Users:', data);
    }
});

// Callback hell / Pyramid of doom (PROBLEM)
getUser(userId, function(user) {
    getOrders(user.id, function(orders) {
        getOrderDetails(orders[0].id, function(details) {
            getPayment(details.id, function(payment) {
                console.log('Payment:', payment);
            });
        });
    });
});

// Solution: Use Promises or async/await
// Modern approach with async/await
async function getPaymentInfo(userId) {
    try {
        const user = await getUser(userId);
        const orders = await getOrders(user.id);
        const details = await getOrderDetails(orders[0].id);
        const payment = await getPayment(details.id);
        return payment;
    } catch (error) {
        console.error('Error:', error);
    }
}

// Higher-order function with callback
function doubleAsync(number, callback) {
    setTimeout(function() {
        callback(number * 2);
    }, 1000);
}

doubleAsync(5, function(result) {
    console.log('Result:', result); // Result: 10 (after 1 second)
});

Interview tip: Mention that callbacks are fundamental to JavaScript's asynchronous programming model. Discuss callback hell (pyramid of doom) and why Promises and async/await are now preferred. Explain that callbacks are still used in array methods (map, filter, forEach) even though they're not asynchronous.

Callback function एक ऐसा function है जो दूसरे function को argument के रूप में pass किया जाता है, और receiving function इसे 'call back' (execute) करता है अपने execution के दौरान किसी point पर।

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

function sayGoodbye() {
    console.log('Goodbye!');
}

greet('John', sayGoodbye);
// Output:
// Hello John
// Goodbye!

// Callback with arguments
function add(a, b, callback) {
    const result = a + b;
    callback(result);
}

add(5, 3, function(sum) {
    console.log('Sum is: ' + sum);
});

// Array methods
const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(num) {
    console.log(num * 2);
});

const doubled = numbers.map(function(num) {
    return num * 2;
});

const evens = numbers.filter(function(num) {
    return num % 2 === 0;
});

// setTimeout callback (async)
console.log('Start');

setTimeout(function() {
    console.log('After 2 seconds');
}, 2000);

console.log('End');

// Node.js file reading
fs.readFile('file.txt', 'utf8', function(err, data) {
    if (err) console.log('Error:', err);
    else console.log('Content:', data);
});

// PROBLEM: Callback hell
getUser(id, function(user) {
    getOrders(user.id, function(orders) {
        getDetails(orders[0].id, function(details) {
            console.log('Details:', details);
        });
    });
});

// SOLUTION: async/await
async function getInfo(id) {
    try {
        const user = await getUser(id);
        const orders = await getOrders(user.id);
        const details = await getDetails(orders[0].id);
        return details;
    } catch (error) {
        console.error(error);
    }
}

इंटरव्यू टिप: बताएं callbacks JavaScript के asynchronous programming model में fundamental हैं। Callback hell (pyramid of doom) discuss करें और समझाएं क्यों Promises और async/await अब prefer किए जाते हैं।

Was this answer clear?