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.
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.
Use a ternary to print 1 item or N items for const n = 1 and const n = 4.
Rewrite this with a guard clause: if (age !== undefined) { if (age >= 18) { console.log("adult"); } else { console.log("minor"); } }.
Explain it without notes
How does an if / else if / else chain decide which block to run?
What is the difference between if and the ternary operator?
What is a guard clause, and why do people use it?
Why can if (count) be a bug?
Preview
Console
Nothing logged yet.Expected console output
closed medium