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

2 comments:

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

    ReplyDelete
  2. 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.

    ReplyDelete