Hello-World
Hello-World

Reputation: 9555

pass functions as a parameter in JavaScript

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());

Upvotes: 0

Views: 94

Answers (3)

Quentin
Quentin

Reputation: 944245

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);

Upvotes: 0

Esailija
Esailija

Reputation: 140236

() 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();
    }

Upvotes: 2

Riz
Riz

Reputation: 10246

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

Upvotes: 2

Related Questions