SmartCodingTips

Understanding Callbacks in JavaScript

A callback is a function passed into another function as an argument, then invoked later inside that function to complete a routine or action.

๐Ÿ“ž Why Use Callbacks?

JavaScript is asynchronous and non-blocking. Callbacks help manage operations that take time, such as network requests or reading files.

๐Ÿงช Basic Example

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

function sayBye() {
    console.log("Goodbye!");
}

greet("Alice", sayBye);

Output:
Hello Alice
Goodbye!

โฑ With setTimeout

setTimeout(function() {
    console.log("Executed after 2 seconds");
}, 2000);

๐Ÿ”„ Callback as Function Parameter

function processUserInput(callback) {
    const name = "Bob";
    callback(name);
}

processUserInput(function(name) {
    console.log("User's name is " + name);
});

โš ๏ธ Callback Hell

Too many nested callbacks can lead to unreadable code.

doSomething(function(result1) {
    doSomethingElse(result1, function(result2) {
        doMore(result2, function(result3) {
            // ...
        });
    });
});
โš ๏ธ Tip: Use Promises or async/await to avoid callback hell.

๐Ÿ“Œ Summary

  • Callbacks are used to run code after a task completes.
  • They allow asynchronous, non-blocking operations.
  • Can be anonymous functions or named functions.