Problem Statement
What is the correct syntax of the ternary operator?
Explanation
The ternary operator syntax is: condition ? valueIfTrue : valueIfFalse
It is a shorthand for if else statements. The condition is evaluated first. If true, it returns the value after the question mark. If false, it returns the value after the colon.
It is the only JavaScript operator that takes three operands, hence the name ternary.
Use it for simple conditions to make code more concise. Avoid nesting multiple ternary operators as it reduces readability.
Code Solution
SolutionRead Only
// Basic ternary
let age = 20;
let status = age >= 18 ? 'Adult' : 'Minor';
console.log(status); // 'Adult'
// Same as if-else
let status2;
if (age >= 18) {
status2 = 'Adult';
} else {
status2 = 'Minor';
}
// In function return
function checkEven(num) {
return num % 2 === 0 ? 'Even' : 'Odd';
}
console.log(checkEven(4)); // 'Even'
console.log(checkEven(7)); // 'Odd'
// Inline usage
let score = 85;
console.log('You ' + (score >= 60 ? 'passed' : 'failed'));
// Avoid deep nesting (hard to read)
let grade = score > 90 ? 'A' : score > 80 ? 'B' : 'C';