JavaScript Functions are ‘first class’ and treated like any other variable. When the function is passed as a parameter to another function, they’re known as a ‘callback’ in JavaScript. That is called when the other function is ready for them.
Example Pass function as parameter JavaScript
Simple example code. If you want to pass a function, just reference it by name without the parentheses:
<html>
<head>
<script type="text/javascript">
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
</script>
</head>
</html>
Output:
But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:
function eat(food1, food2)
{
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args)
{
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);
Source: https://stackoverflow.com
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version