Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.3 — Conditions: if, else and the Ternary
JavaScript · Example 3 of 3

Truthy conditions and the 0 trap

if (stock) can't tell "zero" from "missing". Say what you mean with a comparison.

if runs a block of code only when a condition is truthy, else if and else add other paths, and the ternary condition ? a : b is the expression version that picks one of two values.

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

Write code that prints fizz if n is divisible by 3, buzz if by 5, fizzbuzz if by both, and the number otherwise. Test with n = 15, 9, 10 and 7.

02

Use a ternary to print 1 item or N items for const n = 1 and const n = 4.

03

Rewrite this with a guard clause: if (age !== undefined) { if (age >= 18) { console.log("adult"); } else { console.log("minor"); } }.

Explain it without notes

01

How does an if / else if / else chain decide which block to run?

02

What is the difference between if and the ternary operator?

03

What is a guard clause, and why do people use it?

04

Why can if (count) be a bug?

Truthy conditions and the 0 trap

Console

(nothing was printed)

Expected console output

A: treated as missing
B: stock is known: 0
C: please enter a name
D: sold out