Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda