CallBack Functions

What are callback functions in js and when do we use it ? Can anyone explain in brief with an example.
36 Replies
glutonium
glutonium3mo ago
when u pass one function as an argument to another function thats basically what i callback function is
function sayHello() {
console.log("hello there!");
}

function iCallFunctions(callbackFunction) {
callBackFunction();
}

iCallFunctions(sayHello);
function sayHello() {
console.log("hello there!");
}

function iCallFunctions(callbackFunction) {
callBackFunction();
}

iCallFunctions(sayHello);
here we are passing the sayHello function as an argument to the iCallFunctions() and that function calls the sayHello function
ἔρως
ἔρως3mo ago
a callback function is almost self explanatory: its a function that will be called back later, at possibly some point
glutonium
glutonium3mo ago
another example is
function sayHello() {
console.log("hello there!");
}

document.addEventListener("click", sayHello);
function sayHello() {
console.log("hello there!");
}

document.addEventListener("click", sayHello);
here we will call the function sayHello evertime user clicks
ἔρως
ἔρως3mo ago
remember that callback functions can be executed 0 or more times and it may run after a millisecond or after an hour: nobody knows
Vandana
VandanaOP3mo ago
any usecase/
glutonium
glutonium3mo ago
i just.... showed u .
Jochem
Jochem3mo ago
the array functions use callbacks extensively too 99/100 you'll use callbacks rather than write functions that use them though but they're very common in JavaScript's built-in functions, especially for any asynchronous action. map and the other array functions, .then, addEventListener...
Vandana
VandanaOP3mo ago
yea got it. but what are the advantages by doing so.
document.addEventListener("click", function sayHello() {
console.log("hello there!");
});
document.addEventListener("click", function sayHello() {
console.log("hello there!");
});
glutonium
glutonium3mo ago
when u directly define a callback function u dont need to give it a name
document.addEventListener("click", function() {
console.log("hello there!");
});
document.addEventListener("click", function() {
console.log("hello there!");
});
this is called an anonymous function u give name to a function so u can later refer to that function by that name when writing a callback function directly inside another function, u dont need to give it a name cause there's really no need of it. cause u can only refer to that function using that name only within the function itself. so unless u wanna createa recursive function u dont need to give it a name so for example
document.addEventListener("click", function sayHello() {
console.log("hello there!");
sayHello();
});
document.addEventListener("click", function sayHello() {
console.log("hello there!");
sayHello();
});
it will create an infinity loop, a recursion the first time u click but this is something u wouldnt want for the most part hence no need to give it a name
Jochem
Jochem3mo ago
also: They're both callback functions, one is just named, and one anonymous.
glutonium
glutonium3mo ago
yep
ἔρως
ἔρως3mo ago
people should give it a name anyways its a lot easier to debug sayHello than [anonymous function] by the way, you can pass an async function as a callback, which is very useful if you want to await for fetch for example:
form.addEventListener('submit', async function submit(event) {
event.preventDefault();

let result = await fetch(form.getAttribute('action'), {
method: form.getAttribute('method'),
body: new FormData(form),
});

console.log(result);
});
form.addEventListener('submit', async function submit(event) {
event.preventDefault();

let result = await fetch(form.getAttribute('action'), {
method: form.getAttribute('method'),
body: new FormData(form),
});

console.log(result);
});
Vandana
VandanaOP3mo ago
So basically
callBackFunction();
callBackFunction();
calls sayHello
glutonium
glutonium3mo ago
yes
ἔρως
ἔρως3mo ago
no, you have to pass the function as an argument
glutonium
glutonium3mo ago
ooh ya that
ἔρως
ἔρως3mo ago
otherwise isnt a callback
glutonium
glutonium3mo ago
u have to also pass the function as argument
Vandana
VandanaOP3mo ago
where is the call for submit then??
ἔρως
ἔρως3mo ago
its an event when the hypothetical form is submitted, it triggers the event
glutonium
glutonium3mo ago
iCallFunctions(sayHello); we are passing the sayHello function name so it knows which function to call function iCallFunctions(callbackFunction) here it is receiving the sayHello function as callBackFunction. after u do iCallFunctions(sayHello); , callbackFunction === sayHello then we do callbackFunction() to call the sayHello as callbackFunction
Vandana
VandanaOP3mo ago
And here?
glutonium
glutonium3mo ago
wut about it
Jochem
Jochem3mo ago
addEventListener is special. It registers the callback to be called once an event happens. There's no trigger inside your own code
Vandana
VandanaOP3mo ago
so here it registers async submit callback when submit happens right?
Jochem
Jochem3mo ago
it registers the callback, and that gets called when submit happens, yes it's not async unless you mark it as such with the async keyword, I think, but the code isn't executed right away so it's asynchronous that way?
ἔρως
ἔρως3mo ago
yes, but without the async keyword, you cant use the await and you have to fallback to using the .then with callbacks
Vandana
VandanaOP3mo ago
code isn't executed right away not getting this
ἔρως
ἔρως3mo ago
it gets executed only when the event is triggered and that may never happen or may happen a million times you just dont know
Vandana
VandanaOP3mo ago
Okay.
Jochem
Jochem3mo ago
It's not getting executed in top down order is what I meant, so not in the place in the code where it's written
Vandana
VandanaOP3mo ago
okay i got the working process of callBacks but what is the main benefit? Because somehow things get managed with normal functions only one benefit i can understand is the function may be called later
Jochem
Jochem3mo ago
There's times when you want to write a function that checks the same thing and then executes some code that can differ, but like I said, usually you're consuming functions that require a callback
glutonium
glutonium3mo ago
try to think how u would recreate addEventListener with normal functions without needing a callback or setTimeout or setInterval
Jochem
Jochem3mo ago
As a beginner I just wouldn't worry about how or why you'd write a function that takes a callback as an argument, and just focus on using them with the built-in or library functions
glutonium
glutonium3mo ago
even if u dont need to make one yourself u still have built in functions methods that require u to pass a callback function, so u still need to use them. hence they are important and i agree with Jochem. u dont have to worry about why or where YOU would need to make one but just know time to time u will need to use them when required. And u dont need to worry about how these callback functions are handled when u r dealing with built in methods and functions at least for now. later on at some point u can try to dig into how for example event handlers work and where your callback function gets executed and etc
Want results from more Discord servers?
Add your server