I am vary new to Javascript (just know the syntax) and I am learning AngularJs. Lots of time, I find a function as an argument to other function. Are those callbacks? And also, in what situation, writing functions like this is needed? Thanks.
-
1You could take a look at this http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o – kubuntu Sep 16 '13 at 10:13
-
You should should show us what you are finding confusing. – Vinay Pratap Singh Bhadauria Sep 16 '13 at 10:13
-
Hey Rex. Thanks for the comment. My point was if we can directly calculate something and return it immediately, why to have other function inside a function (which, I guess, does the same task), and also a call to that inner function? – exAres Sep 16 '13 at 10:40
3 Answers
Are those callbacks?
Yes. those are called callbacks.
in what situation, writing functions like this is needed
You need to use callback function when you need to execute something just after the function you called. most probably if you are writing any async code, and if you need to do something when async task is completed, you will definitely need callback functions.for a example, if you need to do call a function when ajax request is completed, you have to use callbacks.
Updated with example based on request.
function myFunction(callback) {
var v1, v2;
// do your stuff and fill the variables.
// Call the callback with filed variables
callback(v1, v2);
}
function callbackFunction(a, b) {
alert(a + " - " + b);
}
myFunction(callbackFunction);

- 23,565
- 5
- 63
- 86
-
Thanks Chamika, it was helpful. But an example would make things more clear for me. Thanks. – exAres Sep 16 '13 at 10:41
-
-
@user2745266, Hope you wil accept the answer once you are eligible to do it. – Chamika Sandamal Sep 16 '13 at 11:53
you have a function like
function addNumbers(nr1, nr2){
return nr1+nr2;
}
then every time you want to add for example 2+5 you just call addNumbers(2, 5)
and it will return 7
the function addNumbers
is a callback function

- 224
- 1
- 2
- 9
Function is just like any other data assigned to a variable, it can be defined, deleted, copied.
They are helpul in cases like
They let you pass functions without the need to name them (which means there are less global variables)
You can delegate the responsibility of calling a function to another function (which means there is less code to write)
- They can help with performance

- 4,667
- 3
- 27
- 58