&&
and ||
are not boolean operators (js)
true && false
->false
true && true
->true
So one might think that the &&
operator can be completely described as follows:
If both values are
true
thentrue
is returned. If one value isfalse
thenfalse
is returned.
And in turn ||
as follows:
If one value is
true
thentrue
is returned. If both values arefalse
thenfalse
is returned.
But these operators can also be used with every other value.
{a: 2} && true
->true
undefined || false
->false
Every value in JS is either truthy or falsy.
All values in JS are truthy except for null
, undefined
, false
, NaN
, 0
, -0
, 0n
, ""
and document.all
see here for more information
Second attempted definition for &&
and ||
&&
If both values are
truthy
thentrue
is returned. If one value isfalsy
thenfalse
is returned.
||
If one value is
truthy
thentrue
is returned. If both values arefalsy
thenfalse
is returned.
I have heard these definitions quite often from beginners. Those definitions are incorrect. Here are the correct definitions:
The correct definition for &&
and ||
&&
returns the first value if it isfalsy
otherwise returns the second.
||
returns the first value if it istruthy
otherwise returns the second.
These definitions also explain the behavior of boolean inputs correctly:
&&
true && true
returnstrue && -> true <-
false && true
returns-> false <- && true
true && false
returnstrue && -> false <-
false && false
returns-> false <- && false
||
true || true
returns-> true <- || true
false || true
returnsfalse || -> true <-
true || false
returns-> true <- || false
false || false
returnsfalse || -> false <-
This mechanism allows the use of those operators in different contexts:
Assign on condition
If maybe
is truthy then it gets assighed otherwise 42
is assigned
const foo = maybe && 42
Only assign 42
when maybe is truthy
otherwise assign the falsy
value.
Most of the time this is used with objects. Another way to write this in that case is:
const foo = maybe ? 42 : undefined
Assign with a default value
const foo = maybe || 42
When maybe
is falsy
then 42
is assigned instead.
There is a third operator ??
which can also be used in that case and which is described in a similar way:
??
Returns the first value if it isnot nullish
otherwise returns the second. Onlynull
andundefined
arenullish
.
const foo = maybe ?? 42
When maybe
is nullish
then 42
is assigned instead.
Order matters
One pitfall when not considering the right definition of these operators is, that one can assume that the order of the operands does not matter, but a && b !== b && a
.
Assume a = true
and b = 42
.
a && b
->42
b && a
->true
a || b
->true
b || a
->42