Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active Jun 14, 2017
Embed
What would you like to do?
A JavaScript files that demonstrates how callbacks work
'use strict';
//=============================================================================
// CallBack.js
//=============================================================================
/*Caller is a function that takes a value, and when the value is done being processed,
* the callback function takes that value and performs another operation on it.
*/
function caller(value, callback) {
callback(value);
}
//Call back function that adds 3 to the output of the caller
function add3(value) {
var result = value + 3;
console.log(result); // we can't use return because return would return to the caller
//and not be returned to outside the caller
}
//Callback function that displays the output of the caller function
function showInformation(value) {
console.log(value);
}
//Example Usage
caller(3, add3); //Display 6 in the console
caller(20, showInformation); //Displays 20 in the console
caller(20, function (value) {
var result = value - 5;
console.log(result);
}); //Displays 15 in the console
//ES6 Example of the above
caller(20, (value) => {
let result = value - 5;
console.log(result);
}); //Display 15 in the console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment