DEV Community

Cover image for CALLBACK FUNCTION
Vinoth Kumar
Vinoth Kumar

Posted on

CALLBACK FUNCTION

CALLBACK FUNCTION IN JS:

A function that is passed as an argument to another function and executed later.

  • A function can accept another function as a parameter.
  • Callbacks allow one function to call another at a later time.
  • A callback function can execute after another function has finished.

EXAMPLE:

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

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

greet("VINOTH", sayBye);
Enter fullscreen mode Exit fullscreen mode

WORKING OF CALLBACK:
JavaScript executes code line by line (synchronously), but sometimes we need to delay execution or wait for a task to complete before running the next function. Callbacks help achieve this by passing a function that is executed later.

console.log("Start");

setTimeout(function () {
    console.log("Inside setTimeout");
}, 2000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

USES OF CALLBACK:

  1. Handling Asynchronous Operations.
  2. Callbacks in Functions Handling Operations.
  3. Callbacks in Event Listeners.(TBD)
  4. Callbacks in API Calls.

HANDLING ASYNCHRONOUS OPERATION:

  1. API requests (fetching data)
  2. Reading files (Node.js file system)
  3. Event listeners (clicks, keyboard inputs)
  4. Database queries (retrieving data)

CALLBACK FUNCTION IN HANDLIING OPERATIONS:
A function needs to execute different behaviors based on input, callbacks make the function flexible.

EXAMPLE:

function calc(a, b, callback) {
    return callback(a, b);
}

function add(x, y) {
    return x + y;
}

function mul(x, y) {
    return x * y;
}

console.log(calc(5, 3, add));    
console.log(calc(5, 3, mul));
Enter fullscreen mode Exit fullscreen mode

CALLBACK IN APICALLS:

  1. Callbacks are useful when retrieving data from APIs.
  2. fetchData() gets data from an API and passes it to handleData() for processing.

Top comments (0)