Home > Blockchain >  Javascript nullish coalescing chained with "or"
Javascript nullish coalescing chained with "or"

Time:07-13

I'm making use of Javascript's "??" operator to assign a default value when the variable is undefined along with "||" when I don't want an undefined value or 0.

For example, the following will prefer "a" when defined or resort to "b".
Then it would prefer 1 when the coalesced value was undefined or 0:

var a, b;
console.log((a ?? b) || 1); // prints "1"

However, the following tweak presents a compilation error.
I'd expect it to either print "1" or "undefined" depending on operation precedence:

var a, b;
console.log(a ?? b || 1); // Uncaught SyntaxError: missing ) after argument list"

Lastly, this compiles and runs but with the caveat that "0" would be an accepted value:

var a, b;
console.log(a ?? b ?? 1); // prints "1"

What's the nuance that I'm missing here?

CodePudding user response:

According to the documentation, you can't chain the nullish coalescing operator with AND or OR:

MDN:

It is not possible to combine both the AND (&&) and OR operators (||) directly with ??. A SyntaxError will be thrown in such cases.

null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError

However, providing parenthesis to explicitly indicate precedence is correct:

(null || undefined) ?? "foo"; // returns "foo"

I found this blog post a helpful resource in thinking through why.

  • Related