Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda