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

171
Vistas
When is it okay/appropriate to use logical assignment in javascript?

I used logical assignments like b = a || [] in Javascript before, and there are many questions on SO about it.
To mention some:

  • What does the construct x = x || y mean?
  • JavaScript variable assignment with OR vs if check
  • How does javascript logical assignment work?

And from what I read, b = a || [] is legit code.

However, I noticed in a recent case (checking for a variable set by another script), that this code does not work as I expected.
I assumed the code would check whether a is falsy, and if so [] would be assigned to b. Since undefined is falsy, I excepted the code to work and assign [] in the case when a was not defined.

But this code causes an error:

let b;

b = a || [];
console.log(b);

a = ["1", "2", "3"];
b = a || [];
console.log(b);

wheras

let b;

b = typeof a == "undefined" ? [] : b;
console.log(b);

a = ["1", "2", "3"];
b = a || [];
console.log(b);

does not. And why is it causing an error, when the error says Uncaught ReferenceError: a is not defined, which implies a is undefined?

When can I use the logical assignment? Only when it is guaranteed that the variable (a) is at least declared?

about 4 years ago · Juan Pablo Isaza
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