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="" >
title>Pass function as a Parameter by</title>
script type="text/javascript">

fOne(p1, p2) {

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

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


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.



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.


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.