Conditional expressions
Conditional logic enables forking the control flow depending on the state, that is, the values available at a given point in the code. Put in a less technical manner, conditionals enable decision making.
A conditional expression is made of three parts:
- a condition, that is, a boolean expression;
- an expression evaluated if, and only if, the condition is true;
- an expression evaluated if, and only if, the condition is false.
The syntax uses a ternary operator with the symbols ?
and :
to
separate the three parts:
const a = 0;
const b = 1;
const min = (a < b) ? a : b; // min == 0
Note: Parentheses are often necessary before ?
, but not always: you
can either rely on the compiler error message or always use
parentheses.