JS101: Ternary Operator
Let’s talk about the ternary operator! The ternary operator is a conditional operator that can efficiently replace several lines of IF statements, allowing us shorter and tidier code. The ternary operator is the only JavaScript operator that takes 3 operands.
IF statement
let pay_babysitter = trueif (pay_babysitter) {
"Paid!"
} else {
"Need to pay!"
}// output: "Paid!"
VS
Ternary Operator
Let’s break it down:
condition ? true : false ? - means IF
: - means ELSE
condition
: An expression that’s used as a condition
true
: An expression in which the condition evaluates to a truthy value
false
: An expression in which the condition is falsy value
Things to keep in mind
Beside false
, other examples of falsy expressions are null
, NAN
, undefined
, 0
, or an empty string(“ “). If the condition represents any falsy values, the result will be executed as a false expression.
Wrapping up
Ternary operators are best for readability when they are used for a single expression. If you find yourself writing an IF/ELSE statement, consider using the ternary operator.