/*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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.