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

169
Views
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
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!