Skip to the workspace
Pebellslearn by building
Expressions & Operators  ›  Lesson

Logical Operators

Logical Operators 12 min

javascript / Logical Operators

Explore each scene at your own pace.

01 · Logical Operators

Logical Operators

Logical Operators

Logical operators short-circuit: && returns the first falsy operand or the last operand; || returns the first truthy operand or the last operand. ?? falls back only for null or undefined.

These operators can return actual values, not only true and false.

See the mechanism

Walk through the modelLogical OperatorsAuthored snapshots of the example; use Run below to test the code.
count0
Zero may be valid application data even though it is falsy.
1 of 3

Follow one example

javascript

0 is falsy, so || chooses 4. It is not null or undefined, so ?? keeps 0. Both nonempty strings are truthy, so && reaches and returns the second one. The right-hand side is evaluated only when it is needed; this matters when it calls a function with side effects. Logical ! produces the boolean negation of an operand’s truthiness.

Predict, change and check

Predict: If 0 is a valid number of saved articles, which fallback preserves it?

Test your explanation: Replace 0 with null and compare both fallback operators. Then try an empty string and explain why the results differ again.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Short-circuiting selects values

&& and || return operand values rather than always returning booleans. Their right operand may not execute. That makes them useful for guards, but it also means a function call on the right can have conditional side effects. Write a normal if when the effect would otherwise be hard to see.

?? defaults only null and undefined. Optional chaining stops a chain at a nullish receiver but does not validate that every non-nullish value has the expected application shape. Avoid treating ?. as a blanket replacement for boundary validation; it can merely turn an earlier data error into a later undefined result.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.