Javascript, callback function example

Javascript callback function is a function that takes a funcation as an paramenter, and inside the body of the function, the function that is passed in will be called. For example, you made a function calculator that takes 3 parameters, the fisrt and the second are numbers, the third is a function. The calculator function will do the calculation of addition, substraction, multiplication and division on the first two parameters. The result will be saved as an json object. This json object will be passed into the callback function which is the third parameter of the calculator function. When you call the calculator function, you pass two numbers and a function. The function takes a parameter, this is the contract between the calcuator function and the user who uses it. In the body of this function, you can do anything you like with the result json object you got from the calculator function.

function calculator(a, b, callback){
	var addition = a + b;
	var substraction = a - b;
	var multiplication = a * b;
	var division = a / b;

	var results={
		addition: addition,
		substraction: substraction,
		multiplication: multiplication,
		division: division

	//Make the third param, callback functin optional
	if (callback && typeof(callback) === "function") {
		callback(results); //call the function that was passed in 

calculator(10, 2);
calculator(10, 2, function(rslt){

Search within Codexpedia

Custom Search

Search the entire web

Custom Search