简体   繁体   中英

Anonymous function in condition in JavaScript

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?

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 
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM