Last active
March 8, 2016 06:08
-
-
Save Tillman32/021837cba82ffc965073 to your computer and use it in GitHub Desktop.
Basic Javascript callback functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Understanding basic Javascript callback functions | |
* By: Brandon Tillman | |
* Website: BrandonTillman.com | |
*/ | |
(function(){ | |
'use strict'; | |
var callback_examples = { | |
// Calls back with a number that is 1-100 | |
get_randomNumber: function(callback) { | |
var randomNumber = Math.floor((Math.random() * 100) + 1); | |
// Returns randomNumber to the anonymous function | |
callback(randomNumber); | |
}, | |
// Calls back with a name via index | |
get_nameByIndex: function(index, callback) { | |
var names = [ | |
"Foo", | |
"Bar", | |
"Mr.Callback"] | |
// Returns the name to the anonymous function | |
callback(names[index]); | |
} | |
}; | |
// Helper function to log the results | |
function logResult(functionName, result) { | |
console.log("The result of %s is: %s", functionName, result); | |
}; | |
// Call our functions | |
callback_examples.get_randomNumber(function(num) { // <-- Anonymous function with the callback | |
logResult("get_randomNumber", num); | |
}); | |
callback_examples.get_nameByIndex(2, function(name){ // <-- Index along with anonymous function | |
logResult("get_nameByIndex", name); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment