Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function into another function

Tags:

javascript

I have a function that is similar to this:

function foo(array1, fun) {
    var n;
    n = a.length;
    var i;
    for (i=0; i<=n; i++) {
        fun(a[i]);
    }
}

Now I want to create a function called mult(x) that I will pass into foo when I call it. My question is what do I put in the parameters of my mult function when I want to call:

foo(some_array, mult(x));
like image 683
Spence Avatar asked Nov 22 '25 16:11

Spence


1 Answers

Just pass in a reference to it (its name only)...

foo(some_array, mult);

Alternatively, pass in an anonymous function...

foo(some_array, function() { ... });

The first argument of this function you pass in with will be set to a[i] like in the body on your function.

like image 87
alex Avatar answered Nov 24 '25 06:11

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!