The ternary operator
Learn to write a conditional expression in one line with ? :.
The ternary operator: a condition in one line
The ternary operator is a short way to write a condition in one line. It has three parts: a condition, ?, and :. The result is a value; this is called a conditional expression.
let result = score >= 50 ? "Pass" : "Fail";When the condition is true the value after ? is returned; when it is false the value after : is returned. This form is especially handy when assigning a value to a variable.
Assigning a value with a ternary
Because a ternary is an expression, you can assign its result directly to a variable. This lets you handle a simple choice in one line instead of three lines with if/else.
let age = 20;
let status = age >= 18 ? "Adult" : "Child";
console.log(status);Use a ternary when it keeps code readable; deeply nested ternaries get hard to read. It is ideal for simple two-way choices.
Exercise Write a Pass/Fail ternary
Write a ternary expression for the score variable. 50 and above is 'Pass', below is 'Fail'. Assign the result to the result variable. The condition must be score >= 50 and use ? with :.
Show example solution
let score = 60;
let result = score >= 50 ? "Pass" : "Fail";
console.log(result);
Test yourself
-
In the expression condition ? a : b, when does b return?
- When the condition is true
- Always
- When the condition is false
- Never
Show answer
When the condition is false — Correct. The value b returns when the condition is false; a returns when it is true.
-
Complete the ternary expression
let score = 60; let result = score >= 50 ____ "Pass" : "Fail";Show answer
let score = 60; let result = score >= 50 ? "Pass" : "Fail"; -
Match the ternary parts
- condition
- An expression returning true/false
- ?
- Comes after the condition
- a
- Value returned when condition is true
- :
- Separates the two branches