||
is a logical or. It returns the first truthy operand* (the last value evaluated). So
var myHeader = headers || {'Content-type':'text/plain'};
Returns "headers" if it's truthy (and if it's null or undefined, that value is coreced into "false"). If it's falsey, it returns the second operand. I don't believe this has a very specific name in javascript, just something general like "default argument value".
|
is a bitwise or. It is a mathematical operation and does something completely different. That operator doesn't even make sense here (and it will generally just produce 0
as a result). Wherever you saw that, it was surely a typo, and they meant to use logical or.
So go with that first method (a = b || c
).
* "Logical or" is also known as "logical disjunction" or "inclusive disjunction". Javascript, like all programming languages, evaluates logical statements using short-circuit evaluation. With logical-or expressions, it evaluates each operand for truthiness and stops on the first true one (and returns that value). If there are no truthy operands, it still had to go through all of them, so it returns the last operand, still the last one it evaluated. Logical and (&&) is similarly short-circuited by stopping on the first falsey operand.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…