Ternary
- Node.js course
- Beginner
- Lesson 39/116
- 4 min
Learn to write a conditional expression in one line with ? :.
The ternary operator
To pick one of two values in a single line you use the ternary operator ? :. The form is condition ? valueA : valueB. If the condition is true, valueA; otherwise valueB is returned.
For example const msg = age >= 18 ? "Adult" : "Child"; makes an assignment in one line. The same logic could be written with if/else, but ternary is shorter. It is especially useful when assigning to a variable or using inside an expression; for complex logic if/else reads better.
Nested ternary
To select among three or more values you can nest ternary: cond1 ? valueA : cond2 ? valueB : valueC. If the first condition is true, valueA; otherwise the second condition is tested.
For example const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"; picks one of three grades in one line. Nested ternary is compact but reduces readability when overused. For more than three branches an if/else if chain is usually better; nested ternary is preferred only for simple assignments.
Practice Adult check
The age variable is set to 20. Declare a variable msg and assign the ternary age >= 18 ? "Adult" : "Child" to it. Then print msg with console.log. The output on a single line must be Adult.
Starter code
const age = 20;
// Declare msg with a ternary and print itSample solution
const age = 20;
const msg = age >= 18 ? "Adult" : "Child";
console.log(msg);Expected output
Adult
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of 5 > 3 ? "a" : "b"?
5 > 3 ? "a" : "b"- true
- "b"
- "a" Correct answer
- 5
Explanation: The condition 5 > 3 is true; the ternary returns "a".
2 Match each part to its meaning
| Term | Meaning |
|---|---|
condition ? |
Tests the condition |
between ? and : |
True value |
after : |
False value |
const x = |
Assignment target |
3 Write the ternary expression
const age = 20;
const msg = age >= 18 ? "Adult" ____ "Child";
const age = 20;
const msg = age >= 18 ? "Adult" : "Child";
Explanation: The : separates the true and false values.