Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Using a simple callback function to perform equally simple calculation functions">
  <meta charset="utf-8">
  <title>Callback: Calculator</title>
</head>
<body>
  <a href="http://metasean.jsbin.com/yohazo/edit?js,console">http://metasean.jsbin.com/yohazo/edit?js,console</a>
</body>
</html>
 
/***********************************************************
  FUNCTIONS TO CALLBACK 
***********************************************************/
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
function divide(a, b) { return a/b; }
function modulus(a, b) { return a % b; }
function randomInt() { 
  return Math.floor(Math.random() * 1000);
}
/***********************************************************
  VARIABLE ASSIGNMENTS 
***********************************************************/
var x = parseInt(prompt("What is X?")) || randomInt();
var y = parseInt(prompt("What is y?")) || randomInt();
/***********************************************************
  OUR AWESOME CALLBACK FUNCTION 
***********************************************************/
function calculate(a, b, callback) {
  return callback(a, b);
}
/***********************************************************
  LOGGING OUR CALLBACK FUNCTION RESULTS
***********************************************************/
console.log("For an x of " + x + " and a y of " + y + ":");
console.log("add      = " + calculate(x, y, add));
console.log("subtract = " + calculate(x, y, subtract));
console.log("multiply = " + calculate(x, y, multiply));
console.log("divide   = " + calculate(x, y, divide));
console.log("modulus  = " + calculate(x, y, modulus));
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
metaseanpro
0viewers