JavaScript Logical Operators

By

Learn the JavaScript logical operators and (&&), or (||), and not (!), including short-circuit evaluation for guarding access and setting default values.

~~~

JavaScript provides us 3 logical operators: and, or and not.

Logical and

Returns true if both operands are true:

<expression> && <expression>

For example:

a === true && b > 3

The cool thing about this operator is that the second expression is never executed if the first evaluates to false. This is called short-circuit evaluation, and it has some practical applications, for example, to check if an object is defined before using it:

const car = { color: 'green' }
const color = car && car.color

If car is null or undefined, the expression stops right there, and color receives that falsy value instead of the code crashing with a TypeError. Modern code often writes this guard as car?.color with optional chaining, but you will read the && version in a lot of existing code.

To be precise, && does not always return a boolean. It returns the first operand if that is falsy, otherwise it returns the second operand. So 'hello' && 42 evaluates to 42.

Logical or

Returns true if at least one of the operands is true:

<expression> || <expression>

For example:

a === true || b > 3

|| short-circuits too, in the opposite direction: if the first operand is truthy, the second is never evaluated, and the first is returned.

This operator is very useful to fallback to a default value. For example:

const car = {}
const color = car.color || 'green'

makes color default to green if car.color is not defined.

There is a trap in that pattern. || replaces every falsy value, not just missing ones. If the real value is 0 or an empty string, it gets thrown away:

const count = 0
count || 10 //10, the real 0 is lost
count ?? 10 //0

When only null and undefined should trigger the default, use ??, the nullish coalescing operator, as in the last line above.

Logical not (!)

Invert the value of a boolean:

let value = true
!value //false

! always returns a boolean, converting the operand first if needed. That is why doubling it is a common idiom to turn any value into true or false:

!!'hello' //true
!!0 //false
Tagged: JavaScript ยท All topics
~~~

Related posts about js: