Anonymous function in condition in JavaScript

Viewed 1038

I would like to use an anonymous function in the condition of an if-statement

Using Firefox 60.7.2.esr running JS 1.5

I tried something like this, figuring it should work like the anonymous function in a forEach statement:

if (function() {
    var b = true;
    if (b) {
        return true;
    } else {
        return false;
    }
}) {
    //do something 
}

My actual anonymous function is quite a bit more elaborate, but in principle it should work the same way. The problem seems to be that the anonymous function does not run at all. Is there a way to make it run?

3 Answers

You need ot use an IIFE - Immediately Invoked Function Expression in this case:

if ( (function(){ var b = true; if (b) { return true; } else { return false; } })() )
{
    //do something 
    console.log("Doing something...");
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

However, the code will be too hard to read (IMO), would be better to do something like this:

function checkForDoSomething()
{
    var b = true;

    if (b)
        return true;
    else
        return false;
}

if ( checkForDoSomething() )
{
    //do something 
    console.log("Doing something...");
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

All you're doing is declaring a function here, it's never actually invoked. Why not just clean up the code a bit, and make it more readable:

const fn = function() {
    var b = true;
    if (b) {
        return true;
    } else {
        return false;
    }
};

if ( fn() ) {
    //do something
    console.log('fn() is true!')
}

Ultimately, to call your function, you need to invoke the function by using (), and optionally passing it parameters. If you want to keep the ugly mess you have there, simply wrap the function in () so you don't get syntax errors, and then directly afterwards invoke it:

if ( (function() {
    var b = true;
    if (b) {
        return true;
    } else {
        return false;
    }
})() ) {
    //do something 
}

To make this work as expected, add parenthesis ( ) around the definition of your anonymous function and then after the closing parenthesis, add () to cause the anonymous function to be invoked:

if ((function() {
    var b = true;
    if (b) {
        return true;
    } else {
        return false;
    }
})()) {
    console.log('if passed');
}

Related