Pass Function as a Parameter in JavaScript

You may at times need to pass a function as a parameter to another function. Here’s an example if you have a similar requirement

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Pass function as a Parameter by DevCurry.com</title>
<
script type="text/javascript">

function
fOne(p1, p2) {
p1(p2);
}

// function literal
var fTwo = function (m1) {
alert(m1 / 10);
};

// pass function fTwo as param
fOne(fTwo, 20 );

</script>
</
head>

As you can see, we use a function literal (var fTwo = function(){}) here. Function fTwo is passed as a parameter to function fOne and the result is output as an alert in fTwo.

OUTPUT

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

Very useful, as usual and thanks for sharing. I searched for this info a lot and could not find it.

Unknown said...

Function literals assigned to variables is one of the foundations that closures are based on. Functions being objects in Javascript is what also makes this concept possible. Douglas Crockford , John Resig, and many others in the field of web development have discussed this concept in great detail.