Lessons · JavaScript · the one-line if
A one-line if that has a value
condition ? whenTrue : whenFalse is an expression: it produces one of the two values, so it can sit inside an assignment or a template.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Choosing a label, a class name, a default: the ternary puts a two-way choice where a value is needed, which an if statement cannot do.
How to think about it
Use it for one choice with two short outcomes. The moment you nest one inside another, switch to if/else; the ternary's value is the point, not its brevity.
Worked example
const size = 5 > 3 ? "big" : "small";The condition is true, so size is big.
console.log(size);big.
const count = 2;For a plural label.
console.log(count + " " + (count === 1 ? "item" : "items"));2 items.
Your turn
Children pay nothing, adults ten.
const fee = age < 12 ? : 10;
Solve one with the tests running
The trap
Nested ternaries are legal and unreadable: a ? b : c ? d : e. Two levels is where an if statement wins.
Practise the one-line if on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.