&& and || are not boolean operators (js)
true && false->falsetrue && true->true
So one might think that the && operator can be completely described as follows:
If both values are
truethentrueis returned. If one value isfalsethenfalseis returned.
And in turn || as follows:
If one value is
truethentrueis returned. If both values arefalsethenfalseis returned.
But these operators can also be used with every other value.
{a: 2} && true->trueundefined || 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
truthythentrueis returned. If one value isfalsythenfalseis returned.
||
If one value is
truthythentrueis returned. If both values arefalsythenfalseis 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 isfalsyotherwise returns the second.
||returns the first value if it istruthyotherwise returns the second.
These definitions also explain the behavior of boolean inputs correctly:
&&
true && truereturnstrue && -> true <-false && truereturns-> false <- && truetrue && falsereturnstrue && -> false <-false && falsereturns-> false <- && false
||
true || truereturns-> true <- || truefalse || truereturnsfalse || -> true <-true || falsereturns-> true <- || falsefalse || falsereturnsfalse || -> 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 nullishotherwise returns the second. Onlynullandundefinedarenullish.
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->42b && a->truea || b->trueb || a->42