I'm brushing up on callback functions and came across the following passage from http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/#
When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.
And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime.
Can someone explain that? Here are two examples they provided.
//The item is a callback function
$(#btn_1).click(function() {
alert(Btn 1 Clicked);
});
Here is another example:
var friends = [Mike, Stacy, Andy, Rick];
friends.forEach(function (eachName, index){
console.log(index + 1 + . + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});
Note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body. So, even though the first jQuery example looked like this:
//The anonymous function is not being executed there in the parameter.
//The item is a callback function
$(#btn_1).click(function() {
alert(Btn 1 Clicked);
});
the anonymous function will be called later inside the function body. Even without a name, it can still be accessed later via the arguments object by the containing function.
For the first example with jquery, what are they saying exactly. If the #btn_1 element is clicked, will the anonymous function be executed? I am assuming it will be executed if the button is clicked, but the wording from the passage was confusing?
Similarly, for the second example, do they not need to call the function that they passed as an argument bc its anonymous?