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);
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");
USES OF CALLBACK:
- Handling Asynchronous Operations.
- Callbacks in Functions Handling Operations.
- Callbacks in Event Listeners.(TBD)
- Callbacks in API Calls.
HANDLING ASYNCHRONOUS OPERATION:
- API requests (fetching data)
- Reading files (Node.js file system)
- Event listeners (clicks, keyboard inputs)
- 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));
CALLBACK IN APICALLS:
- Callbacks are useful when retrieving data from APIs.
- fetchData() gets data from an API and passes it to handleData() for processing.
Top comments (0)