call back practice

by ClarenceDowns

HTML

A:
<input type='text' id='varA' />
<br/>B:
<input type='text' id='varB' />
<br/>
<input type='button' onclick="screen()"id='screen' value='Display on screen' />
<br/>
<input type='button' onclick="alrt()" id='alrt' value='Display in alert' />
<br/>
<div id='demo'>

</div>
<div id='demo2'>

</div>
<div id='demo3'>

</div>

JavaScript

/*function displayInScreen(aVar){
document.getElementById('demo').innerHTML = "Demonstrates display in Div: " + aVar;
}
function displayInAlrt(aVar){
alert("Demonstrates display in alert: " + aVar);
}

function screen(){
var a = document.getElementById('varA').value;
var b = document.getElementById('varB').value;
document.getElementById("demo2").innerHTML = "I should run second";
document.getElementById("demo3").innerHTML = "I should run third";
multiply(a, b, displayInScreen);
}

function alrt(){
var a = document.getElementById('varA').value;
var b = document.getElementById('varB').value;
multiply(a, b, displayInAlrt);

}
function multiply(a, b, callback){
c = a * b;
callback(c);
}
*/


function greeting(name){
alert("hello " + name);
}

function processUserInput(callback){
var name = prompt('Please enter your name');
callback(name);
}
processUserInput(greeting);

function calculate(num1, num2, callbackFunction) {
    return callbackFunction(num1, num2);
}

function calcProduct(num1, num2) {
    return num1 * num2;
}

function calcSum(num1, num2) {
    return num1 + num2;
}
// alerts 75, the product of 5 and 15
alert(calculate(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(calculate(5, 15, calcSum));
/*
First a function calculate is defined with a parameter intended for callback: callbackFunction. Then a function that can be used as a callback to calculate is defined, calcProduct. Other functions may be used for callbackFunction, like calcSum. In this example, calculate() is invoked twice, once with calcProduct as a callback and once with calcSum. The functions return the product and sum, respectively, and then the alert will display them to the screen.

In this primitive example, the use of a callback is primarily a demonstration of principle. One could simply call the callbacks as regular functions, calcProduct(num1, num2). Callbacks are generally used when the function needs to perform events before the callback is executed, or when the...