Mixed Operations
Evaluating a long line
A line with five operators is five small steps. Find the operator JavaScript applies first, replace it and its operands with the value, and write the shorter line underneath. Repeat until one value is left.| Step order | Operators | Within the row |
|---|---|---|
| 1 | ( ), including the parentheses of Math.floor( ) | innermost first |
| 2 | - (negation) | applies to the one value after it |
| 3 | ** | right to left |
| 4 | * / % | left to right |
| 5 | + - | left to right |
| 6 | === !== < > | after all the arithmetic |
Four rules decide most of these lines.
Division keeps the fraction.
-23 / 8 is -2.875, and the fraction stays until a function such as Math.floor deals with it. Math.floor rounds down, toward negative infinity, so it gives -3. Math.trunc cuts the fraction off and gives -2. They differ only on a negative value that isn't whole.A remainder keeps the sign of the number on its left.
-11 % 3 is -2, not 1.A minus sign written straight before a power is rejected.
-6 ** 2 is a SyntaxError, so the program doesn't run at all. Write (-6) ** 2, which is 36, or -(6 ** 2), which is -36.Once a step meets text, + joins. The other arithmetic operators turn text such as "6" into a number, but + glues, and it goes left to right like every other step.
When you write out the steps, copy every operator you haven't used yet onto the next line. If a step drops one, every line after it is wrong too.