Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.2 — Logical Operators
JavaScript · Example 2 of 4

Short-circuiting: the right side may never run

Without the cart && guard, cart.items would throw a TypeError. ?. (ES2020) does the same job more neatly: cart?.items.length.

&&, || and ! combine true/false conditions, but && and || really return one of their operands and stop early (short-circuit); ?? picks a fallback only for null or undefined, and ||=, &&= and ??= assign on the same rules.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const input = "";, print the input or the text (empty) if it's empty.

02

Given const page = { size: 0 };, set size to 20 only if it is missing, and add sort: "name" if sort is missing. Print the object.

03

Predict, then check: console.log(null ?? 0 || 5) — why doesn't it run?

Explain it without notes

01

What do && and || actually return?

02

What is short-circuit evaluation, and how is it useful?

03

When should you use ?? instead of ||?

04

What do ||=, &&= and ??= do?

Short-circuiting: the right side may never run

Console

(nothing was printed)

Expected console output

checked a
checked c
checked e
checked f
null