||
is the logical-or operator. See here. It evaluates to true
if at least one of the operands is true. You can only use it with boolean operands; it is an error to use it with integer operands.
// Example
var one = true || bar(); // result is true; bar() is never called
var two = true | bar(); // result is true; bar() is always called
|
is the or operator. See here. If applied to boolean types, it evaluates to true
if at least one of the operands is true. If applied to integer types, it evaluates to another number. This number has each of its bits set to 1 if at least one of the operands has a corresponding bit set.
// Example
var a = 0x10;
var b = 0x01;
var c = a | b; // 0x11 == 17
var d = a || b; // Compile error; can't apply || to integers
var e = 0x11 == c; // True
For boolean operands, a || b
is identical to a | b
, with the single exception that b
is not evaluated if a
is true. For this reason, ||
is said to be "short-circuiting".
If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?
As noted, the difference isn't irrelevant, so this question is partially moot. As for a "best practice", there isn't one: you simply use whichever operator is the correct one to use. In general, people favor ||
over |
for boolean operands since you can be sure it won't produce unnecessary side effects.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…