Skip to content

Instantly share code, notes, and snippets.

@jll90
Created January 22, 2016 02:05
Show Gist options
  • Save jll90/2597f3336d40251cfb61 to your computer and use it in GitHub Desktop.
Save jll90/2597f3336d40251cfb61 to your computer and use it in GitHub Desktop.
Example of JavaScript callbacks.
// executes a single function
function single(callback){
callback();
}
function b(){
console.log("I'm b");
}
function d(){
console.log("I'm d");
}
//prints: I'm b
single(b);
//prints: I'm d
single(d);
// pass multiple functions
function multiple(fns){
if (fns.constructor === Array){
var length = fns.length;
for (i = 0; i < length; i++){
fns[i](); //executes ith function
}
} else{
fns(); //executes the function passed to it
}
}
// prints I'm b
multiple(b);
// prints I'm b followed by I'm d
multiple([b,d]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment