Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
The ternary operator is a one-line shortcut for writing simple if-else statements. It's called "ternary" because it has three parts: a condition, a value if true, and a value if false.
Check this
If YES
If NO
The question you're asking (true or false?)
The value returned when condition is true
The value returned when condition is false
let age = 20;
let status;
if (age >= 18) {
status = 'Adult';
} else {
status = 'Minor';
}
console.log(status);
// Output: AdultTakes 9 lines of code
let age = 20; let status = age >= 18 ? 'Adult' : 'Minor'; console.log(status); // Output: Adult
Only 3 lines! Much cleaner ✨
Practice with different scenarios
Simple yes/no decisionsage >= 18 ? 'Adult' : 'Minor'
Assigning one of two valueslet status = isOnline ? 'Active' : 'Offline'
Quick inline checksprice > 100 ? 'Expensive' : 'Affordable'
Complex conditions
Multiple checks get messy fast
Nested ternaries
Hard to read and understand
Multiple actions needed
Use regular if-else for that
// Too confusing! Which value goes where? let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
// Much easier to read and understand let grade; if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else grade = 'F';
Show different messages based on user login status
Apply discounts for members automatically
Ternary operator turns 5+ lines into just 1 line
Question mark for true, colon for false
Perfect for quick yes/no decisions
Don't put ternaries inside ternaries - use if-else