<h1>Pass through a function as a parameter to a function</h1>
<div>
<ul>
<li>Important warning: Make sure what you pass through is in fact a reference to a function (ie not a string)</li>
<li><a href="http://stackoverflow.com/questions/13286233/javascript-pass-function-as-parameter">http://stackoverflow.com/questions/13286233/javascript-pass-function-as-parameter</a></li>
</div>
JavaScript
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world from function 2!');
}
function1(function2); //This will work
/* Below this will not work because we are passing
* through the string "function2" instead of a reference
* the actual function we call function2 */
try {
function1("function2"); //This breaks because the quotation make function2 a string
}
catch(err) {
alert('It broke, here\'s why: "' + err.message + '"\n\nIn other words...\ntypedef "function2" == string \ntypedef function2 == function');
}
//Note this does NOT work since you're passing through a string:
//function("function2");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.