I realize that you most probably have your answer now, but I am posting an answer anyways because: a. the question is important and will surely have a sufficient amount of future viewers. b. the other answer does not explain the relationship between ToBoolean
and ||
very well c. I would have to change and add too much if i were to edit the other answer instead, so...
In JavaScript, both the ||
and &&
logical operators will coerce their operands to boolean
if they aren't booleans already, using the abstract ToBoolean
operation.
You can see the effects of this ToBoolean
operation using the Boolean
constructor or an implicit !!
conversion:
Boolean(foo);
!!foo;
Either of the 2 lines above will convert foo
to a boolean.
But how do they do it ?
It's much simple: If the variable foo
is either null
, undefined
, NaN
, 0
, or ""
(you could also say false
, but that's a tad obvious), it will become false
; in all other cases, it will become true
.
Values that become false
after a ToBoolean
coercion (which can be performed by either of the above lines) are called "falsy values". Can you guess what values which become true
after a ToBoolean
operation are called ?
Here is an example of some ToBoolean
operations:
const foo = "abc";
console.log(!!foo); // Prints out "true"
console.log(Boolean(foo)); // Same thing as above
const bar = "";
const baz = undefined;
console.log(Boolean(bar)); // Prints out "false"
console.log(Boolean(baz)); // Prints out "false"
/* Prints out "abc", because both "bar" and "baz" will become "false" after "||" coerces them to "boolean"*/
console.log(bar || baz || foo);
So, in your example, if aaa
is either of the "falsy" values I listed above, JavaScript will skip it and go to the next operand of ||
, if that operand is not a falsy value, it will be selected by ||
.
As a sidenote, ||
will always stop at the first "truthy" value, if there are no truthy values, it will select the last operand.
Here is a link to
ToBoolean
in the specs.