Skip to content

&& and || are not boolean operators (js)

Posted on:August 15, 2023

&& and || are not boolean operators (js)

So one might think that the && operator can be completely described as follows:

If both values are true then true is returned. If one value is false then false is returned.

And in turn || as follows:

If one value is true then true is returned. If both values are false then false is returned.

But these operators can also be used with every other value.

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 then true is returned. If one value is falsy then false is returned.

||

If one value is truthy then true is returned. If both values are falsy then false 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 is falsy otherwise returns the second.

|| returns the first value if it is truthy otherwise returns the second.

These definitions also explain the behavior of boolean inputs correctly:

&&

||

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 is not nullish otherwise returns the second. Only null and undefined are nullish.

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.