Emmanuel Akinfulubi

JavaScriptRecursion

Fast exponentiation with recursion in JavaScript

Intermediate · 3 min read

Raising a number to a power means multiplying it by itself a set number of times. 2 to the power 10, written 2^10, is ten 2s multiplied together: 1024. Powers show up in compound interest, in file sizes (a kilobyte is 2^10 bytes) and in the math behind encryption.

In this tutorial you will write power(base, exp) recursively, handle zero and negative exponents, and then build a much faster version that needs about a dozen calls where the simple one needs over a thousand. You need to know what a function and an if are. Recursion is explained as we go.

Powers in plain words

A power contains a smaller power of the same number:

Worked example

2^4 = 2 × 2 × 2 × 2
    = 2 × (2 × 2 × 2)
    = 2 × 2^3

So power(2, 4) can be "2 times power(2, 3)". A function that answers by calling itself on a smaller input is recursive. It needs a base case where it stops: any number to the power 0 is 1.

A negative exponent means "one over": 2^-2 is 1 / 2^2, which is 0.25.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

5 Raise a number to a power

fair

Compute base ** exponent by recursion. Then halve the work using the fact that x^8 is (x^4)^2.

Stuck? Three hints, smallest first
  1. 1. Anything to the power 0 is 1, and that is your base case.
  2. 2. A negative exponent is 1 / power(base, -exponent).
  3. 3. For the fast version: if the exponent is even, square the half-power; if odd, peel one factor off.

Step 1: the simple recursion

Base case first, then one multiplication and a smaller call:

Step 1

function power(base, exp) {
  if (exp === 0) return 1;
  return base * power(base, exp - 1);
}
console.log(power(8, 2));  // 64
console.log(power(2, 10)); // 1024
console.log(power(7, 0));  // 1
console.log(power(-3, 3)); // -27

A negative base works without any extra code, because the multiplications take care of the signs.

Step 2: the negative exponent trap

Now try a negative exponent with Step 1's function:

JavaScript

function power(base, exp) {
  if (exp === 0) return 1;
  return base * power(base, exp - 1);
}
try {
  power(2, -2);
} catch (e) {
  console.log(e.constructor.name); // 'RangeError'
}

exp starts at -2 and goes to -3, -4 and so on. It moves away from 0, so the base case never arrives, and JavaScript throws RangeError: Maximum call stack size exceeded. The fix is to turn a negative exponent into a positive one before recursing:

Step 2

function power(base, exp) {
  if (exp === 0) return 1;
  if (exp < 0) return 1 / power(base, -exp);
  return base * power(base, exp - 1);
}
console.log(power(2, -2)); // 0.25

Step 3: the squaring trick

The simple version needs one call per step of the exponent. 2^1024 takes 1,025 calls. There is a shortcut. Squaring a number means multiplying it by itself, and

Worked example

2^8 = (2^4)^2      work out 2^4 once, then square it
2^9 = (2^4)^2 × 2  odd exponent: one leftover factor

So for an even exponent, find the power of half the exponent and square it. For an odd one, do the same and multiply by the base once more. Each call halves the exponent instead of taking 1 off.

Step 4: write the fast version

Math.floor(exp / 2) halves the exponent and drops any .5. exp % 2 === 0 checks whether it is even:

Step 4

function powerFast(base, exp) {
  if (exp === 0) return 1;
  if (exp < 0) return 1 / powerFast(base, -exp);
  const half = powerFast(base, Math.floor(exp / 2));
  return exp % 2 === 0 ? half * half : half * half * base;
}
console.log(powerFast(2, 10)); // 1024
console.log(powerFast(5, 7));  // 78125
console.log(powerFast(2, 20) === 2 ** 20); // true

Storing the result in half matters. Writing powerFast(base, ...) * powerFast(base, ...) would make two calls each time and throw the saving away.

Step 5: count the calls

Claims about speed are easy to make, so count them. Each counter goes up once per call:

Step 5

let slow = 0;
let fast = 0;
const countSlow = (b, e) => { slow++; return e === 0 ? 1 : b * countSlow(b, e - 1); };
const countFast = (b, e) => {
  fast++;
  if (e === 0) return 1;
  const h = countFast(b, Math.floor(e / 2));
  return e % 2 === 0 ? h * h : h * h * b;
};
countSlow(2, 1024);
countFast(2, 1024);
console.log(slow, fast); // 1025 12

The fast version halves 1024 down to 0 in eleven steps, plus the first call. (2^1024 itself is too big for a Number and comes out as Infinity, but the call count is what this step measures.)

The full solution

The panel has both versions with call counters, and checks for zero, negative exponents, negative bases and agreement with the ** operator. Press Run to see the output.

The answer

// Straightforward: n multiplications, so n stack frames.
function power(base, exp) {
  if (exp === 0) return 1;
  if (exp < 0) return 1 / power(base, -exp);
  return base * power(base, exp - 1);
}

// Exponentiation by squaring: about log2(n) steps instead of n.
function powerFast(base, exp) {
  if (exp === 0) return 1;
  if (exp < 0) return 1 / powerFast(base, -exp);
  const half = powerFast(base, Math.floor(exp / 2));
  return exp % 2 === 0 ? half * half : half * half * base;
}

// Count the calls so the difference is not just a claim.
let slow = 0;
let fast = 0;
const countSlow = (b, e) => { slow++; return e === 0 ? 1 : b * countSlow(b, e - 1); };
const countFast = (b, e) => {
  fast++;
  if (e === 0) return 1;
  const h = countFast(b, Math.floor(e / 2));
  return e % 2 === 0 ? h * h : h * h * b;
};
countSlow(2, 1024);
countFast(2, 1024);

console.log("8^2 =", power(8, 2), "  (the example)");
console.log('2^10 =', power(2, 10));
console.log('2^-2 =', power(2, -2));
console.log('calls for 2^1024 — plain:', slow, ' by squaring:', fast);

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test("the example: 8 squared is 64", power(8, 2), 64);
test('2^10 is 1024', power(2, 10), 1024);
test('anything to the 0 is 1', power(7, 0), 1);
test('JavaScript agrees that 0^0 is 1', power(0, 0), 0 ** 0);
test('to the power 1 is itself', power(9, 1), 9);
test('a negative exponent inverts', power(2, -2), 0.25);
test('a negative base with an odd power stays negative', power(-3, 3), -27);
test('and turns positive on an even power', power(-3, 2), 9);
test('the fast version agrees everywhere', [[8, 2], [2, 10], [7, 0], [2, -2], [-3, 3], [5, 7]].every(([b, e]) => powerFast(b, e) === power(b, e)), true);
test('and matches the ** operator', powerFast(2, 20), 2 ** 20);
test('squaring needs far fewer calls', fast < slow / 50, true);

Squaring turns 1025 calls into 12, and the assertion above proves the ratio rather than asserting it in prose. The exp % 2 split is the whole trick: an even exponent is one squaring of the half, an odd one is that plus a single leftover factor. In real code you would write base ** exp, but this pattern reappears whenever squaring is cheap and multiplying is not — modular exponentiation in cryptography is exactly this function.

Common mistakes

  • Not handling negative exponents. The exponent moves away from 0 and the recursion never stops.
  • Calling the half-power twice. f(half) * f(half) makes the fast version as slow as the simple one. Store it in a variable.
  • Writing ^ for powers. In JavaScript 2 ^ 3 is a bitwise operation and gives 1. Use 2 ** 3 or Math.pow(2, 3).

Try it yourself

  1. Add a counter to powerFast and find how many calls powerFast(3, 100) makes.
  2. Write powerLoop(base, exp) with a for loop and check it agrees with power for exponents 0 to 10.
  3. Change powerFast so it takes a third argument mod and returns the remainder after dividing by mod at every step. Check that powerFast(2, 10, 1000) gives 24.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.