Created
June 24, 2025 22:00
-
-
Save gungunfebrianza/7a1afc550fd3d456c777c67704c05720 to your computer and use it in GitHub Desktop.
One-Line If-Else Statement in JavaScript (Ternary Operator)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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