CALL-BACK FUNCTIONS

A Call Back Functions are the functions which is passed as an argument in another functions.

For Example:

app/page.tsx
1// Example of a function that takes a callback
2function doSomething(callback) {
3    callback()
4}
5
6// Define a callback function
7function callbackFunction() {
8  console.log("Callback executed!");
9}
10
11// Call the function with the callback
12doSomethingAsync(callbackFunction);
13
14//output -> Callback executed!

Js Built-in Functions using call-back functions

Event Handlers:

Callbacks are frequently used in event handling. For example, the addEventListener method uses a callback to respond to events:

app/script.js
1document.getElementById("myButton").addEventListener("click", function() {
2  console.log("Button clicked!");
3});

Array Methods

  • map: Creates a new array by applying a callback function to each element in the original array.
app/script.js
1const numbers = [1, 2, 3, 4, 5];
2const squared = numbers.map((num) => {
3    return num
4});
5//here , map took a callback function as an argument