Search code examples
javascriptlogical-or

Logical OR in JavaScript


I ran into a case where I have run both functions in a JavaScript or expression:

function first(){
    console.log("First function");
    return true;
};

function second(){
    console.log("Second function");
    return false;
};

console.log(!!(first()||second()));

In this case it will output:

"First function"

true

In C# there is a logical (|) OR that is different from a conditional or (||) that will make sure both expressions are evaluated:

Func<bool> first = () => { Console.WriteLine("First function"); return true; };
Func<bool> second = () => { Console.WriteLine("Second function"); return false; };
Console.WriteLine(first() | second());

This will output:

In this case it will output:

"First function"

"Second function"

true

I can't seem to find any info on how to implement the same logic in JavaScript without running the expressions beforehand:

function first(){
    console.log("First function");
    return true;
};

function second(){
    console.log("Second function");
    return false;
};

var firstResult = first();
var secondResult = second();

console.log(firstResult||secondResult);

Is there a way I can implement a C# logical OR in JavaScript?

Thanks.


Solution

  • Just use | (Bitwise OR):

    function first(){
        console.log("First function");
        return true;
    };
    
    function second(){
        console.log("Second function");
        return false;
    };
    
    console.log(!!(first()|second()));

    Read more about logical operators (||, !!, etc...) and bitwise operators (|, &, etc...) in JavaScript.