1

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?

heyufool1
  • 63
  • 7
  • Possible duplicate of [Why JavaScript forbids combining Nullish operator (`??`) with And (`&&`), OR (`||`) operators?](https://stackoverflow.com/q/69580087/1048572) – Bergi Jul 12 '22 at 22:34

1 Answers1

1

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.

esinator
  • 76
  • 5