Search code examples
javascriptif-statementbitwise-operators

If statement using Bitwise AND Operators to force evaluations


I have several independent functions which return either true or false depending other conditions. When they all return true I want an action to occur, however I want all of the functions to run regardless of how many return false. If I just wanted to check all of the functions were returning true I would use:

if (func1() && func2() && func3() ){
    //Some code
}

The problem with this is that if one of the functions returns false all of the functions to the right will not execute. One method I haven't tried before is using Bitwise AND Operators (&) in the if expression, which would look like:

if (func1() & func2() & func3() ){
    //Some code
}

I have briefly tested this method and it seems to be producing the desired outcome however I could not find this method used elsewhere and I am wondering if there is any reason that this could produce a unexpected outcome?

Also is there is a good reason not to compare the results of the functions using this method?


Solution

  • If they're just returning boolean true/false operations, then it'll work as expected:

    if (true & false & true) 
    

    would simply be "false".

    But if they're turning (say) integers, then you're going to get unexpected results:

    if (10 & 100 & 32)
    

    would be

    if (b1010 & b1100100 & b100000)
    

    and evaluate to false.