Arithmetic & Exponentiation

Every arithmetic operator, including ** and the quirks of division and remainder.

Syntaxbase ** exponent ((n % m) + m) % m

You 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 first

Remainder 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

Try it yourself
Loading editor…
Press Run to execute the code.

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.

Example Β· js
console.log(2 ** 10);      // 1024
console.log(-2 ** 2);     // SyntaxError β€” wrap: -(2**2)
console.log(+("42"));    // 42 β€” string to number

Increment and decrement

Contrasts postfix i++ (returns old value) with prefix ++i (returns new value).

Example Β· js
let i = 5;
console.log(i++); // 5 – returns THEN increments
console.log(i);   // 6
console.log(++i); // 7 – increments THEN returns

Integer division and remainder

Uses Math.floor and % to split a minute count into hours and remaining minutes.

Example Β· js
const totalMinutes = 137;
const hours = Math.floor(totalMinutes / 60); // 2
const mins  = totalMinutes % 60;             // 17
console.log(`${hours}h ${mins}m`); // "2h 17m"

Discussion

  • Be the first to comment on this lesson.
Arithmetic & Exponentiation β€” JavaScript | SoundsCode