Function passed to function

Hi All,

Can someone explain to me how the attached code works?
I understand the 3 and 4 are passed as the x and y parameters and the function is passed as the z parameter.. But i don understand  what parameters are being passed to: function(x,y) { return x * y}??
Also, what is happening in the following line:


function funcObject(x,y,z) {

function testFunction() {

// third parameter is function
funcObject(3,4,function(x,y) { return x * y})


Open in new window

Who is Participating?
Roman GhermanSenior Software EngineerCommented:

Javascript allows you to pass any object as a parameter to a function.

A function is basically an object in javascript, this is why in the example you provided you have a function as the third parameter.

"alert(z(x,y));" - will call the function passed in parameter z with the two parameters: x and y.

this will show an dialog containing the TEXT: 12.  
x*y = 12;
No params are passed to function(x,y) { return x * y}
It's function definition that is passed to funcObject()

12 will be the result of alert
oggiemcAuthor Commented:
Thanks for reply guys..Unfortunately i still dont see where the actual multiplication of x * y is happening??

\\ "alert(z(x,y));" - will call the function passed in parameter z with the two parameters: x and y.

so what you are saying is that above line is equivalent to:
alert(function(x,y) { return x * y}(x,y));   // i.e z = function(x,y) { return x * y}?

it all looks a bit confusing to me, and im not really sure what is the point of this technique?? Perhaps someone can enlighten me / explain in a bit more detail?
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Roman GhermanSenior Software EngineerCommented:
yes, that is correct.

that syntax is called anonymous function.
oggiemcAuthor Commented:

So all the above line means is:

The z function i.e function(x,y) { return x * y} is called, and the x,y parameters are passed in to it?? I understand it is called an anonymous function, however i do not understand why such functions are used? What is the advantage over declarative functions?

Roman GhermanSenior Software EngineerCommented:
yes the x,y parameters are passed in to it

take a look at this page with explanations:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.