Command Palette

Search for a command to run...

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

The ternary is an expression

The ternary sits inside a template literal and on the right of =, places where an if statement can't go. The nested one at the end works, but an if chain would be easier to read.

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?

The ternary is an expression

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

closed medium