coalescing in Javascript?

In C# you can do the following:

string y = null;
string x = y ?? "sup stallion"; //x = "sup stallion" since y is null.

Where The ?? operator is the null-coalescing operator.

And in Javascript I've seen something similar:

var headers;
var myHeader = headers || {'Content-type':'text/plain'}; //myHeaders = {'Content...

I've also seen: (The 2nd code snippet on the page)

var headers;
var myHeader = headers | {'Content-type':'text/plain'};

Is there a difference between the two? What is this pattern called...default parameter?


|| 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.


I am not familiar with the second pattern. The two patterns I am aware of:

1) Your first pattern is a basic logical or operator. If the first value is falsy then the second value is assigned.

2) The second pattern is called a ternary assignment, which is similar in logic to a basic if condition, but the syntax is slightly different.

var test = (typeof myTest === "string") ? firstValue : secondValue;

In this pattern the question mark separates the condition from the values and the colon separates the values. Tertiary assignments can be nested so that one of the values contains another tertiary.


Not really an expert to this but the || is a Logical Operator and | is a Bitwise Operator

链接地址: http://www.djcxy.com/p/73370.html

上一篇: 在JavaScript中使用初始化对象

下一篇: 在Javascript中合并?