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.



Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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.

Avelis 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.