Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Javascript nullish coalescing chained with "or"

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!