HTML and CSS Reference
In-Depth Information
Both functions consist of three main steps. The first step is repeated in both functions; the
second step is specific to each function; and the third step does the same thing in each case, but
with different data. Having functions defined in this way simply works. If getting results is all you are
interested in, then feel free to stop here.
The whole point is that a simplistic solution like this may possibly work well in a simple scenario.
As complexity grows, you may end up with a great deal of duplicated code—which is bad because it
forces you to make changes in several places and if you miss making the change in one place you can
introduce bugs that can be truly hard to find and fix. Callback functions help by making the previous
code not only smaller, but also far easier to read.
To illustrate the point, you'll start by creating a single function that orchestrates the various steps
for both the sum and multiplication; you can call this function handleNumbers .
function handleNumbers(operationCallback) {
// STEP 1: COLLECT INPUT DATA
var numbers = new Array();
for (var i = 1; i < arguments.length; i++) // start from 1 to skip callback
function
numbers.push(arguments[i]);
// STEP 2: PERFORM OPERATION
var result = operationCallback(numbers);
// STEP 3: DISPLAY RESULTS
alert(result);
}
Now define a couple of highly specific functions: one that sums and one that multiplies all received
parameters.
function doSum(numbers) {
var result = 0;
for (var i = 0; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
function doMultiply(numbers) {
var result = 1;
for (var i = 0; i < numbers.length; i++) {
result *= numbers[i];
}
return result;
}
Search WWH ::




Custom Search