Many math equations require a mix of operations like addition, subtraction, multiplication, and division.
JavaScript follows the standard order of operations for evaluating a math expression.
Take a look at the following examples:
Expression | Result |
---|---|
2 + 3 * 4 |
14 |
8 - 4 / 2 |
6 |
Multiplication and division happen before addition and subtraction, even if they appear later in the expression.
Parentheses
Sometimes we need to manually declare which operations should happen first. We can do this by wrapping that operation in parentheses:
Expression | Result |
---|---|
(2 + 3) * 4 |
20 |
(8 - 4) / 2 |
4 |
The same numbers and operators lead to a different result when we use parentheses to change the order of operations.