Page 169 - JavaScript
P. 169
Chapter 18: Callbacks
Examples
Simple Callback Usage Examples
Callbacks offer a way to extend the functionality of a function (or method) without changing its
code. This approach is often used in modules (libraries / plugins), the code of which is not
supposed to be changed.
Suppose we have written the following function, calculating the sum of a given array of values:
function foo(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
Now suppose that we want to do something with each value of the array, e.g. display it using
alert(). We could make the appropriate changes in the code of foo, like this:
function foo(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
alert(array[i]);
sum += array[i];
}
return sum;
}
But what if we decide to use console.log instead of alert()? Obviously changing the code of foo,
whenever we decide to do something else with each value, is not a good idea. It is much better to
have the option to change our mind without changing the code of foo. That's exactly the use case
for callbacks. We only have to slightly change foo's signature and body:
function foo(array, callback) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
callback(array[i]);
sum += array[i];
}
return sum;
}
And now we are able to change the behaviour of foo just by changing its parameters:
var array = [];
foo(array, alert);
https://riptutorial.com/ 126

