38

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?

Alan
  • 45,915
  • 17
  • 113
  • 134
  • 2
    possible duplicate of [Is there a "null coalescing" operator in JavaScript?](http://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript) – Alex Angas Feb 04 '15 at 22:54

5 Answers5

37

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

Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • I added a link to the original question. But here it is: http://csausdev.wordpress.com/2010/12/17/dependency-injection-in-node-js/ – Alan Mar 26 '12 at 01:22
  • I know that in general prefer `===` to prevent type coercion, but in this case, is this acceptable javascript, or am I learning a bad habit? – Alan Mar 26 '12 at 01:24
  • @Alan, you're right that type coercion is usually to be avoided, but this is one of the minority cases where it's *usually* okay. The exception is when the "default" value might be something falsey (e.g. The literal "false" vs "undefined", for example). In that case, you'll want to use the ternary conditional operator. – Ben Lee Mar 26 '12 at 01:28
  • @Alan, regarding the link showing `http | require('http')`, I believe that must just be a typo in that blog post. The author surely meant `http || require('http')`. – Ben Lee Mar 26 '12 at 01:36
5

Nullish coalescing operator is supported now by javascript(es2020)

As the mozilla doc says:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples.

// Assigning a default value to a variable (old way but in some cases we need this)
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty);     // 42 and not 0
console.log(message); // "hi!" and not ""

// Assign default value when we want to skip undefined/null only
// in most cases we need this, because (0,"",false) are valid values to our programs
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

For more info read this example provided by kent c dods about fallback to default value in the past and now: https://kentcdodds.com/blog/javascript-to-know-for-react#nullish-coalescing-operator

SeyyedKhandon
  • 5,197
  • 8
  • 37
  • 68
  • For those who use Babel: [Babel 7.8.0 supports](https://babeljs.io/blog/2020/01/11/7.8.0) the new ECMAScript 2020 features by default: you don't need to enable individual plugins for nullish coalescing (??), optional chaining (?.) and dynamic import() anymore with preset-env. – Michael Freidgeim Jun 04 '21 at 23:09
3

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.

Murph
  • 9,985
  • 2
  • 26
  • 41
austincheney
  • 1,189
  • 9
  • 11
2

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

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

ES2020 has brought nullish coalescing operator (??) to javascript.

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

lordvcs
  • 2,466
  • 3
  • 28
  • 37