Sceptic
Sceptic

Reputation: 1659

Usage of bitwise or to run functions inside if statement

I have a situation where I want to make sure that some or all functions used inside an if statement are run regardless of the statement is already true. I know I can use an bitwise operator for this.

function test1() {
    console.log('called1');
    return true;
}
function test2() {
    console.log('called2');
    return false;
}

if(test1() | test2()) {
    console.log('done');
}
// called 1
// called 2
// done

if(test1() | test2() | test1() || test2()) {
    console.log('done');
}
// called 1
// called 2
// called 1
// done

Is this a correct usage for the bitwise or operator though? I can't find this usage described anywhere.

Upvotes: 1

Views: 47

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074575

Is this a correct usage for the bitwise or operator though?

It's valid, because your functions return values (in your case, booleans) which can be successfully coerced to useful numeric values (false => 0, true => 1), which can be OR'd together, and which when OR'd together do give you a value that you can usefully coerce back to boolean.

As for correct, well, if I saw it in code, I would tend to think it was a typo and that you intended to write || instead. You'd at least have to comment it to flag up the intention of avoiding short-circuiting.

But it's perfectly valid and not pushing the edge of anything, it's clearly-specified behavior.

Upvotes: 4

Related Questions