Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical OR in JavaScript [duplicate]

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.

like image 765
Philip Avatar asked Sep 04 '19 08:09

Philip


2 Answers

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.

like image 181
MrGeek Avatar answered Oct 05 '22 21:10

MrGeek


You could call all functions by collecting the values and then check the values.

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

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

console.log([first(), second()].some(Boolean));
like image 37
Nina Scholz Avatar answered Oct 05 '22 23:10

Nina Scholz