Arithmetic & Exponentiation
Every arithmetic operator, including ** and the quirks of division and remainder.
base ** exponent
((n % m) + m) % mYou already know + - * /. Let us go a level deeper, because arithmetic in JavaScript has a few sharp edges worth respecting.
The exponentiation operator
** raises a number to a power. It is right-associative, which means 2 ** 3 ** 2 is 2 ** (3 ** 2), not (2 ** 3) ** 2. That surprises almost everyone the first time.
console.log(2 ** 10); // 1024
console.log(2 ** 3 ** 2); // 512, because 3**2 happens firstRemainder is not modulo
The % operator keeps the sign of the dividend, so -7 % 3 is -1, not 2. If you need a true positive modulo, wrap it: ((n % m) + m) % m.
Unary plus and negation
A single + in front of a value coerces it to a number, the shortest way to parse numeric strings.
Example
When to use it
- Use the exponentiation operator to compute compound interest over N years in a financial calculator.
- Apply the increment operator in a read-position tracker that steps through bytes in a binary buffer.
- Use unary minus to negate a temperature value when converting between Celsius and a display scale.
More examples
Exponentiation and unary plus
Shows ** for exponentiation, the unary + coercion trick, and the parsing ambiguity with negative bases.
console.log(2 ** 10); // 1024
console.log(-2 ** 2); // SyntaxError β wrap: -(2**2)
console.log(+("42")); // 42 β string to numberIncrement and decrement
Contrasts postfix i++ (returns old value) with prefix ++i (returns new value).
let i = 5;
console.log(i++); // 5 β returns THEN increments
console.log(i); // 6
console.log(++i); // 7 β increments THEN returnsInteger division and remainder
Uses Math.floor and % to split a minute count into hours and remaining minutes.
const totalMinutes = 137;
const hours = Math.floor(totalMinutes / 60); // 2
const mins = totalMinutes % 60; // 17
console.log(`${hours}h ${mins}m`); // "2h 17m"
Discussion