Decisions and repetition

JavaScript Logical Operators

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

JavaScript gives us three logical operators: and, or, and not.

Logical and

&& returns the first falsy operand, or the last operand if every value is truthy:

<expression> && <expression>

Example:

a === true && b > 3

If the left side is falsy, JavaScript skips the right side. That is short-circuit evaluation.

Guard property access before the dot:

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

If car is null, the expression stops and color gets that falsy value instead of throwing.

Modern code often writes car?.color with optional chaining, but you will still see && guards in older code.

Note: && does not always return a boolean. 'hello' && 42 evaluates to 42.

Logical or

|| returns the first truthy operand, or the last operand if none are truthy:

<expression> || <expression>

Example:

a === true || b > 3

Use || to fall back to a default:

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

color becomes 'green' when car.color is missing.

The trap: || replaces every falsy value, not just missing ones:

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.

Logical not (!)

! inverts a boolean after converting the operand:

let value = true
!value //false

Double negation converts any value to strict true or false:

!!'hello' //true
!!0 //false

Combine operators for real guards:

const canEdit = user && user.role === 'admin'

Here && stops before .role when user is missing, and the comparison only runs on a real object.

Remember that && and || return operands, not always booleans. That behavior powers defaults and guards, but it also hides type information. Read the expression knowing what type each branch returns.

Run null && 'backup', undefined || 'default', and !!'' in the console. Each shows how short-circuit and coercion interact.

Lesson completed