0

How do I pass functions as a parameter in JavaScript.

In the code below if I call whatMustHappen (TWO(),ONE()) I want to them to fall in the sequence of the x and the y on the whatMustHappen function.

Right now it fires as it sees it in the parameter.

var ONE = function() {
    alert("ONE");
}
var TWO = function() {
    alert("TWO");
}
var THREE = function() {
    alert("THREE");
}
var whatMustHappen = function(x, y) {
    y;
    x;
}
whatMustHappen(TWO(), null);
whatMustHappen(TWO(), ONE());

3 Answers 3

2
var whatMustHappen = function(x, y) {
        if (y) y();
        if (x) x();
    }
whatMustHappen(TWO, null);
whatMustHappen(TWO, ONE);
Sign up to request clarification or add additional context in comments.

1 Comment

which error and why ? due to null ? OP should take care of that. Updated my answer anyway.
2

() invokes a function and returns its result. To pass a function, you simply pass it like any other variable:

whatMustHappen(TWO, ONE);

In whatMustHappen function, you can then call them:

var whatMustHappen = function(x, y) {
        if( y ) y();
        if( x ) x();
    }

Comments

0

If you want to pass a function, don't call it (with (args)).

function foo () {
    alert("foo");
}

function bar (arg) {
    alert("Function passed: " + arg);
    arg();
}

bar(foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.