Skip to content

Instantly share code, notes, and snippets.

@gungunfebrianza
Created June 24, 2025 22:00
Show Gist options
  • Save gungunfebrianza/7a1afc550fd3d456c777c67704c05720 to your computer and use it in GitHub Desktop.
Save gungunfebrianza/7a1afc550fd3d456c777c67704c05720 to your computer and use it in GitHub Desktop.
One-Line If-Else Statement in JavaScript (Ternary Operator)
1. Simple value assignment
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
// status = 'Adult'
2. Function return
function getFee(isMember) {
return isMember ? '$2.00' : '$10.00';
}
getFee(true); // Returns "$2.00"
3. Executing different operations
const isMorning = true;
isMorning ? console.log('Good morning!') : console.log('Good day!');
4. Multiple operations (using comma operator)
let x = 10;
x > 5 ? (console.log('Big'), x *= 2) : (console.log('Small'), x /= 2);
5. Nested ternary (for multiple conditions)
const grade = 85;
const result = grade >= 90 ? 'A' : grade >= 80 ? 'B' : grade >= 70 ? 'C' : 'F';
// result = 'B'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment