Reputation: 171
I understand how short-circuit evaluation works when using the logical or operator in JavaScript, but I've run into what seems to be a weird edge case I don't fully understand.
So, this snippet works the way I would expect:
const a = 'a' || 'b';
with a
having a value of 'a'
.
And of course, this also works the way I would expect:
const a = false || 'b';
with a
having a value of 'b'
.
However, I've run into this weird situation with an expression like this:
const a = true || true || true ? 'a' : 'b';
where a
now has a value of 'a'
. I've tried other combinations, such as:
const a = true || false || true ? 'a' : 'b';
and a
still has a value of 'a'
.
Another thing to try is something like this:
const fn = () => true ? 'a' : 'b';
const a = true || fn();
and of course a
has a value of true
, and fn
is never called.
What's going on here?
Upvotes: 1
Views: 59
Reputation: 42480
A logical OR ||
is evaluated from left to right and the first value that evaluates to a truthy value is returned, or the last one if none of them evaluates to true
.
In this case, the first true
trivially evaluates to true
, thus the whole condition returns true
:
true || true || false
As a result, the first expression of the ternary operator is evaluated, in this case 'a'
:
const a = true || true || true ? 'a' : 'b';
For this reason, a
equals 'a'
.
The same logic applies to the other cases you listed.
Upvotes: 1