Brevity is the Soul of Wit
Sometimes we just need to assign one of two values to a variable depending on a condition. For this, there is the " question mark " or ternary operator.
Why " ternary " ?
Because it has three operands: condition ? value_if_true : value_if_false.
let accessAllowed = (age > 18) ? "Yes" : "No";
Recommendations
- Use it only for short assignments.
- Do not nest ternary operators inside each other unless you want your colleagues (and yourself in a week) to hate you.
Caution
Do not use ? for executing actions.
BAD: (age > 18) ? alert('Ok') : alert('No');
GOOD: if (age > 18) { alert('Ok'); }
The ternary operator should RETURN a value, not execute commands.
Tip
Parentheses around the condition (age > 18) are not mandatory, but they greatly improve code readability.