Home / javascript / What is callback Function?

What is callback Function?

A callback function, in programming, is a function that is passed as an argument to another function and is executed after some operation or event has occurred. Callback functions are commonly used in asynchronous programming, where tasks are performed concurrently and the program doesn’t wait for one task to finish before moving on to the next.

For example, in JavaScript, a callback function might be passed to an asynchronous function like setTimeout() to be executed after a certain delay. Here’s a simple example:

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

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

// Using greet() with a callback function
greet("Alice", sayGoodbye);

In this example, sayGoodbye() is a callback function that gets executed after the greet() function finishes its operation of printing a greeting message.

About admin

Check Also

What is hoisting in javascript with example?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the …

Leave a Reply

Your email address will not be published. Required fields are marked *