Chain ternary operators correctly in JavaScript
Beginner · 3 min read
The ternary operator is a one-line if. It picks one of two values: condition ? valueIfTrue : valueIfFalse. It is perfect for small choices like "Paid" or "Unpaid", or picking a price band. You can chain several to make a ladder of choices. But it has one trap that catches almost everyone: mixed with + and no brackets, it gives the same answer every time.
In this tutorial you will pick a fare band (luxury, standard or economy) with a chain of ternaries, and then build a message with + and a ternary to find that trap and fix it. You need to know what if, comparisons like >=, and strings are.
The shape of a ternary
const age = 20;
const label = age >= 18 ? 'adult' : 'child';
console.log(label); // adult
Read it as: "is age >= 18? If yes, 'adult', otherwise 'child'." The ? asks the question and the : separates the two answers.
Statement versus expression
An if is a statement: it does things. A ternary is an expression: it produces a value. That's why you can put a ternary straight after = or return, or inside a template string, where an if can't go.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
96 The ternary, and the brackets it needs
easyPick a fare band with a chain of ternaries. Then build a message with + and a ternary in the same expression, without brackets, and work out why the answer never changes.
Stuck? Three hints, smallest first
- 1. A ternary is an expression, so it can be returned or assigned directly.
- 2. Chained ternaries read as a ladder because
? :groups to the right. - 3.
+binds tighter than? :, so the whole concatenation becomes the condition.
Step 1: return a ternary
const shortest = (a, b) => (a < b ? a : b);
console.log(shortest(4, 9)); // 4
console.log(shortest(9, 4)); // 4
The ternary is the whole body of the arrow function. The brackets around it aren't required here, but they make it clear where the ternary starts and ends.
Step 2: a chain of ternaries
Fares are in kobo (100 kobo make one naira). The underscore in 500_00 only makes it easier to read. A trip of ₦500 or more is luxury, ₦300 or more is standard, anything less is economy:
const tier = (kobo) => (kobo >= 500_00 ? 'luxury' : kobo >= 300_00 ? 'standard' : 'economy');
console.log(tier(600_00)); // luxury
console.log(tier(500_00)); // luxury
console.log(tier(350_00)); // standard
console.log(tier(120_00)); // economy
The "otherwise" part of the first ternary is another ternary. JavaScript groups chained ternaries from the right, so it reads as a ladder: check the top band, else check the next, else the last. The checks go from the highest band down, so each one only has to test the lower bound.
Note tier(500_00) gives 'luxury': >= puts a fare exactly on the boundary into the higher band. Always test the boundaries.
Step 3: laying out a long chain
A long chain on one line gets hard to read. Put each choice on its own line:
const tier = (kobo) =>
kobo >= 500_00 ? 'luxury'
: kobo >= 300_00 ? 'standard'
: 'economy';
console.log([600_00, 350_00, 120_00].map(tier)); // [ 'luxury', 'standard', 'economy' ]
Same code, easier to scan. With more than three bands, a lookup table or a switch is usually easier to change than a longer ladder.
Step 4: the trap with +
Now build a message saying whether the fare was paid:
const paid = false;
const wrong = 'fare: ' + paid ? 'yes' : 'no';
console.log(wrong); // yes
paid is false, yet the answer is 'yes'. And it's not even 'fare: yes', just 'yes'.
Here's why. JavaScript does + before ? :. So the line really means:
const paid = false;
const wrong = ('fare: ' + paid) ? 'yes' : 'no';
console.log('fare: ' + paid); // fare: false
The condition is the string 'fare: false'. Any non-empty string counts as true in a condition, so the ternary always picks 'yes', whatever paid holds. Nothing throws, and if you only ever test with paid = true, you'd never notice.
Step 5: brackets fix it
Put brackets around the ternary, so it runs first and its result is joined on:
const paid = false;
const right = 'fare: ' + (paid ? 'yes' : 'no');
console.log(right); // fare: no
Template strings avoid the problem too, because ${ } already acts as brackets:
const paid = true;
console.log(`fare: ${paid ? 'yes' : 'no'}`); // fare: yes
The full solution
The answer panel has tier, shortest, and the wrong and right messages. Its checks cover each band, the boundary at ₦500, the always-'yes' trap and the bracketed fix. Press Run to see the output.
const tier = (kobo) => (kobo >= 500_00 ? 'luxury' : kobo >= 300_00 ? 'standard' : 'economy');
const shortest = (a, b) => (a < b ? a : b);
const paid = false;
// + happens first, so the condition is the string 'fare: false', which is truthy.
const wrong = 'fare: ' + paid ? 'yes' : 'no';
// The brackets are what make it a choice between two words.
const right = 'fare: ' + (paid ? 'yes' : 'no');
console.log('wrong:', wrong, '| right:', right);
console.log([600_00, 500_00, 350_00, 120_00].map(tier));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the top band', tier(600_00), 'luxury');
test('a boundary belongs to the higher band', tier(500_00), 'luxury');
test('the middle band', tier(350_00), 'standard');
test('and the bottom', tier(120_00), 'economy');
test('a chain of ternaries reads as a ladder', [600_00, 350_00, 120_00].map(tier), ['luxury', 'standard', 'economy']);
test('+ binds tighter than ?:, so this is always yes', wrong, 'yes');
test('the brackets are not decoration', right, 'fare: no');
test('and a ternary is an expression, so it can be returned as it stands', shortest(4, 9), 4);
The ternary earns its place when both branches produce a value for the same slot — assigning one of two fares, choosing a word inside a template. Where the branches do two different things, an if says so more clearly, and where there are four bands rather than three, a lookup table (exercise 87) or a switch (exercise 97) is easier to extend.
'fare: ' + paid ? 'yes' : 'no' is the trap, and it is silent: + runs first, so the condition is the non-empty string 'fare: false', every non-empty string is truthy, and the result is 'yes' regardless of what paid holds. Nothing throws, and a test that only checks the happy path passes. Put brackets round a ternary whenever it shares an expression with anything else.
Common mistakes
- Mixing a ternary with
+and no brackets. The+runs first and the whole string becomes the condition. - Checking bands in the wrong order. Test
>= 300_00first and a ₦600 fare comes out as standard. - Using a ternary to do two different actions. If the branches do things instead of producing a value, use an
if.
Try it yourself
- Add a fourth band,
'premium'for ₦1,000 or more, to the top of the ladder. - Write
plural(n)that returns'1 seat'or'3 seats'using a ternary inside a template string. - Rewrite
tierwithifandreturn. Which version is easier to read?