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
0Follow one example
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.