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
glutonium2mo 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
ἔρως
ἔρως2mo ago
a callback function is almost self explanatory: its a function that will be called back later, at possibly some point
glutonium
glutonium2mo 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
ἔρως
ἔρως2mo 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
Vandana2mo ago
any usecase/
glutonium
glutonium2mo ago
i just.... showed u .
Jochem
Jochem2mo 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
Vandana2mo 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
glutonium2mo 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
Jochem2mo ago
also: They're both callback functions, one is just named, and one anonymous.
glutonium
glutonium2mo ago
yep
ἔρως
ἔρως2mo 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
Vandana2mo ago
So basically
callBackFunction();
callBackFunction();
calls sayHello
glutonium
glutonium2mo ago
yes
ἔρως
ἔρως2mo ago
no, you have to pass the function as an argument
glutonium
glutonium2mo ago
ooh ya that
ἔρως
ἔρως2mo ago
otherwise isnt a callback
glutonium
glutonium2mo ago
u have to also pass the function as argument
Vandana
Vandana2mo ago
where is the call for submit then??
ἔρως
ἔρως2mo ago
its an event when the hypothetical form is submitted, it triggers the event
glutonium
glutonium2mo 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
Vandana2mo ago
And here?
glutonium
glutonium2mo ago
wut about it
Jochem
Jochem2mo ago
addEventListener is special. It registers the callback to be called once an event happens. There's no trigger inside your own code
Vandana
Vandana2mo ago
so here it registers async submit callback when submit happens right?
Jochem
Jochem2mo 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?
ἔρως
ἔρως2mo ago
yes, but without the async keyword, you cant use the await and you have to fallback to using the .then with callbacks
Vandana
Vandana2mo ago
code isn't executed right away not getting this
ἔρως
ἔρως2mo 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
Vandana2mo ago
Okay.
Jochem
Jochem2mo 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
Vandana2mo 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
Jochem2mo 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
glutonium2mo ago
try to think how u would recreate addEventListener with normal functions without needing a callback or setTimeout or setInterval
Jochem
Jochem2mo 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
glutonium2mo 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