What is the Ternary Operator?
The ternary operator is a shorthand way to write simple if-else statements in one line!
⚡ javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Syntax: condition ? valueIfTrue : valueIfFalse
// Regular if-else
const age = 20
let status
if (age >= 18) {
status = 'Adult'
} else {
status = 'Minor'
}
// Ternary (same thing, shorter!)
const status = age >= 18 ? 'Adult' : 'Minor'
console.log(status) // 'Adult'The three parts:
- condition - What to check
- ? - Question mark separator
- valueIfTrue - Result if condition is true
- : - Colon separator
- valueIfFalse - Result if condition is false