Sub topic 3
Arithmetic Operators, ** and the Sign of %
This chapter assumes you can write variables and functions, run code in Node.js or a browser console, and know what === and typeof do. It also assumes you have read the earlier chapters: JavaScript has a single Number type, stored as a 64-bit IEEE 754 double.
Every arithmetic operator works on that one type. The language has no integer division and no separate integer type for %. Most surprises with these operators come from three things: how + decides between adding and joining strings, how ** interacts with unary minus, and which operand's sign % keeps.
The Operator Set
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` | Addition or string concatenation | `7 + 2` | `9` |
| `-` | Subtraction | `7 - 2` | `5` |
| `*` | Multiplication | `7 * 2` | `14` |
| `/` | Division (always floating point) | `7 / 2` | `3.5` |
| `%` | Remainder | `7 % 2` | `1` |
| `**` | Exponentiation | `7 ** 2` | `49` |
| unary `+` | Convert to number | `+"7"` | `7` |
| unary `-` | Convert and negate | `-"7"` | `-7` |
| `++` / `--` | Increment / decrement | `x++` | old value of `x` |
Each binary operator also has a compound assignment form: +=, -=, *=, /=, %=, and **=.
let total = 10;
total += 5; // 15
total *= 2; // 30
total **= 2; // 900
total %= 7; // 4
console.log(total); // 4
console.log(7 / 2); // 3.5, never 3
console.log(Math.trunc(7 / 2)); // 3, integer division toward zero
console.log(Math.trunc(-7 / 2)); // -3/ never truncates. If you want integer division, wrap the result in Math.trunc (rounds toward zero) or Math.floor (rounds toward negative infinity). A later chapter compares those rounding functions.
Increment and Decrement: Prefix vs Postfix
The postfix form returns the value from before the change. The prefix form returns the value after it.
let a = 5;
const b = a++; // b gets 5, then a becomes 6
let c = 5;
const d = ++c; // c becomes 6, then d gets 6
console.log(a, b, c, d); // 6 5 6 6The difference matters only when you use the expression's value. When i++ sits alone as a statement, both forms behave the same.
How + Chooses Between Adding and Concatenating
Five of the binary arithmetic operators always convert their operands to numbers. + is the exception. It first converts objects to primitive values. If either operand is then a string, it joins the two as strings.
console.log("3" + 4); // "34"
console.log("3" - 4); // -1
console.log("3" * "4"); // 12
console.log(1 + 2 + "3"); // "33" (1 + 2 runs first, giving 3, then "3" is appended)
console.log("1" + 2 + 3); // "123" (a string from the start)
console.log(true + 1); // 2
console.log([] + 1); // "1" ([] becomes "")+ evaluates left to right, so the position of the first string changes the result. Values from form fields, URL parameters, and localStorage are strings. If you add them with + and forget to convert them, you get "1020" where you expected 30. Convert them explicitly first. The chapter on type conversion covers Number(), parseInt, and unary plus in detail.
Exponentiation with **
** is the operator form of Math.pow. It accepts fractional and negative exponents.
console.log(2 ** 10); // 1024
console.log(2 ** -1); // 0.5
console.log(9 ** 0.5); // 3
console.log(2 ** 0.5); // 1.4142135623730951
console.log((-8) ** (1/3)); // NaN (negative base, fractional exponent)
console.log(NaN ** 0); // 1 (anything to the power 0 is 1)Right Associativity
** groups from the right, as it does in mathematical notation. Every other arithmetic operator groups from the left.
console.log(2 ** 3 ** 2); // 512, same as 2 ** (3 ** 2) = 2 ** 9
console.log((2 ** 3) ** 2); // 64
console.log(100 / 10 / 2); // 5, same as (100 / 10) / 2The Unary Minus Gotcha
In mathematical notation, -2² means -(2²) = −4. Many programming languages read it as (-2)² = 4 instead. To avoid that ambiguity, JavaScript makes a unary operator directly on the left of ** a syntax error.
// console.log(-2 ** 2); // SyntaxError: Unary operator used immediately before exponentiation expression
console.log((-2) ** 2); // 4
console.log(-(2 ** 2)); // -4
const x = -2;
console.log(x ** 2); // 4, fine: the minus is part of the stored valueBecause the error happens at parse time, the whole script fails to load. This is safer than silently giving a result you didn't mean, but it can surprise you when you port a formula from another language. Add parentheses to say which reading you mean.
Precedence Summary
| Precedence (high to low) | Operators | Associativity |
|---|---|---|
| 1 | `x++`, `x--` | n/a |
| 2 | `++x`, `--x`, unary `+`, unary `-` | n/a |
| 3 | `**` | right to left |
| 4 | `*`, `/`, `%` | left to right |
| 5 | `+`, `-` | left to right |
** sits above * and /, so 2 * 3 ** 2 is 18. % has the same precedence as * and /, so 10 - 7 % 3 is 10 - 1 = 9. Use parentheses whenever a reader might have to stop and work out the grouping.
The Sign of %
% is a remainder operator, not a modulo operator. The result takes the sign of the dividend (the left operand). The divisor's sign has no effect.
console.log(7 % 3); // 1
console.log(-7 % 3); // -1
console.log(7 % -3); // 1
console.log(-7 % -3); // -1
console.log(-6 % 3); // -0 (a negative zero; equals 0 under ===)Internally, a % b computes a - b * q, where q is a / b truncated toward zero. For -7 % 3, q is -2, so the result is -7 - (3 * -2) = -1.
The modulo used in mathematics and in Python's % uses floor division instead, so its result takes the sign of the divisor. The two agree when both operands are positive and differ otherwise.
| Expression | JavaScript `%` (truncated) | Floored modulo |
|---|---|---|
| `7, 3` | `1` | `1` |
| `-7, 3` | `-1` | `2` |
| `7, -3` | `1` | `-2` |
| `-7, -3` | `-1` | `-1` |
Writing a True Modulo
Wrapping values into a range is the common case where the sign matters: cycling through array indexes, days of the week, or angles. The ((n % m) + m) % m pattern gives floored modulo for any nonzero m.
function mod(n, m) {
return ((n % m) + m) % m;
}
console.log(mod(-7, 3)); // 2
console.log(mod(7, -3)); // -2
console.log(mod(7, 3)); // 1
const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const today = 1; // Mon
console.log(days[(today - 3) % 7]); // undefined, because index -2 doesn't exist
console.log(days[mod(today - 3, 7)]); // "Fri"The bug in the next-to-last line is common in carousels and circular buffers. Moving "back" past index 0 produces a negative index, and arrays return undefined for it without throwing.
% with Fractions and Special Values
% works on floating-point numbers, so it carries the same representation error as any other floating-point operation.
console.log(5.5 % 2); // 1.5
console.log(0.5 % 0.1); // 0.09999999999999998, not 0
console.log(5 % 0); // NaN
console.log(Infinity % 2); // NaN
console.log(5 % Infinity); // 50.5 % 0.1 is not zero because the stored value of 0.1 is slightly larger than one tenth, so it fits into 0.5 only four whole times. Don't use % on decimal fractions to test whether one value divides another. Scale to integers first (for example, work in cents instead of dollars), or compare with a tolerance, as covered in the floating-point precision chapter.
Unlike many languages, JavaScript does not throw when you divide by zero. 5 / 0 gives Infinity, and 5 % 0 gives NaN. The next chapters look at these special values.
Common Errors at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| Adding string input with `+` | `"10" + 20` gives `"1020"` | Convert with `Number()` first |
| Expecting `/` to truncate | `7 / 2` gives `3.5` | `Math.trunc(7 / 2)` |
| Writing `-x ** 2` | SyntaxError on load | `-(x ** 2)` or `(-x) ** 2` |
| Using `%` as modulo on negatives | `-1 % 5` gives `-1` | `((n % m) + m) % m` |
| Odd check `n % 2 === 1` | Fails for negative odd numbers | `n % 2 !== 0` |
| `%` on decimals | `0.5 % 0.1` is not `0` | Scale to integers |
Exercise
What does each line print, and why? (a) console.log("5" + 3 - 1); (b) console.log(2 ** -1 ** 2); — hint: will this line even run? (c) console.log(-13 % 5);
Show answer
(a) 52. "5" + 3 concatenates to "53", then - converts it back to a number: 53 - 1 = 52. (b) It prints 0.5. Here the minus applies to 1 inside the exponent, not to the base 2, so it is allowed. Right associativity groups it as 2 ** ((-1) ** 2) = 2 ** 1 = 2... check again: the unary minus binds to 1 ** 2 only as the right operand's base, so the expression is 2 ** ((-1) ** 2), and (-1) ** 2 is 1, which makes the result 2. Only a unary operator immediately to the left of the base of ** is forbidden. (c) -3. The remainder takes the sign of the dividend -13, since -13 - 5 * (-2) = -3.
Exercise
Write a function wrapIndex(i, length) that maps any integer i, including negative values, to a valid index for an array of that length. Use it to show that index -1 of a 4-element array maps to 3 and index 9 maps to 1.
Show answer
function wrapIndex(i, length) { return ((i % length) + length) % length; } then console.log(wrapIndex(-1, 4)); // 3 and console.log(wrapIndex(9, 4)); // 1. Adding length lifts a negative remainder into the range from 0 to length, and the second % handles the case where the first remainder was already nonnegative.