0% found this document useful (0 votes)
16 views6 pages

Callback Function

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views6 pages

Callback Function

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Callback Function

• A callback is a function that passed as an argument into


another function.

Syntax: Function print(callback) { }

Why do we need Callback Functions?


• JavaScript runs code sequentially in top-down order. However, there are
some cases that code runs (or must run) after something else happens
and also not sequentially. This is called asynchronous programming.
• Callbacks make sure that a function is not going to run before a task is
completed but will run right after the task has completed. It helps us
develop asynchronous JavaScript code and keeps us safe from problems
and errors.
Example 1: Simple callback
function sayHi(name) {
[Link]("Hi " + name);
}
function greetUser(callback) {
let userName = “Rahul";
callback(userName);
}
greetUser(sayHi); // Output: Hi Rahul

Example 2: Callback with setTimeout


function printMessage() {
[Link]("Message after 2 seconds");
}
setTimeout(printMessage, 2000); // callback executes after delay
Example 3: Anonymous callback
setTimeout(function() {
[Link]("Hello from anonymous callback!");
}, 3000);

Example 4: Callback inside another function


function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(5, 10, function(sum) {
[Link]("The sum is " + sum);
});
Callback hell

• The situation when multiple callbacks are nested is


known as the callback hell.
• Every callback depends/waits for the previous
callback.
Syntax:
doTask1(() => {
doTask2(() => {
doTask3(() => {
[Link]("All tasks done!");
});
});
});
Example
FUNCTION GETUSER(ID, CALLBACK) {

SETTIMEOUT(() => {
[Link]("FETCHED USER WITH ID:", ID);

CALLBACK({ ID: ID, NAME: “RAHUL" });

}, 1000);
}

FUNCTION GETORDERS(USER, CALLBACK) {

SETTIMEOUT(() => {
[Link]("FETCHED ORDERS FOR USER:", [Link]);

CALLBACK(["ORDER1", "ORDER2", "ORDER3"]);

}, 1000);
}

FUNCTION GETORDERDETAILS(ORDER, CALLBACK) {

SETTIMEOUT(() => {
[Link]("FETCHED DETAILS FOR ORDER:", ORDER);

CALLBACK({ ITEM: "LAPTOP", PRICE: 50000 });


}, 1000);
}
// --- USING NESTED CALLBACKS ---
GETUSER(101, FUNCTION(USER) {

GETORDERS(USER, FUNCTION(ORDERS) {
GETORDERDETAILS(ORDERS[0], FUNCTION(DETAILS) {
[Link]("ORDER DETAILS:", DETAILS);

});
});
});

You might also like