1 year ago

#364714

test-img

jost21

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:

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?

javascript

error-handling

variable-assignment

logical-operators

assignment-operator

0 Answers

Your Answer

Accepted video resources