Reputation: 95
I learn now that a callback is function that pass to argument. but I can do it without so what is the point? for example
function i()
{
alert("callback");
}
function p(a)
{
for(r=0;r<100;r++)
{document.write(r);}
a();
}
p(i);
or
function i()
{
alert("callback");
}
function p()
{
for(r=0;r<100;r++)
{document.write(r);}
i();}
I searched but could not find an answer
Upvotes: 0
Views: 152
Reputation: 45155
So to take you example, yes if you want to call i()
in function p()
you can just go ahead and do that. But what if you want a function just like p()
accept that it calls j()
at the end instead of i()
? Well, that's easy, you pass a function as a parameter for p()
to call at the end instead of hardcoding it.
It's about flexibility. There's no need to do it for the sake of doing it, but there are many cases where it's useful.
So let me try and come up with a simple example, let's say we have a function called sum()
that adds up all the elements of an array. Now let's say somewhere in our program we want to sum not all the elements, but some of the elements, maybe only the elements over a certain value, or every other element. If we set up sum so that it could take, in addition to the array to work on, a function parameter that will call filter
(which if left null, we'll just sum all the elements by default), we could make our sum()
function much more useful and avoid writing a whole bunch of different sum functions.
Also, as Quentin already answered, it's especially useful for asychronous functions.
Upvotes: 2
Reputation: 944530
Callbacks are usually used when you want to do something with some data that isn't immediately available.
For example, to process some data from an HTTP response when the response arrives or to perform an action based on where a mouse click occurred when the mouse button is clicked.
Upvotes: 3