Calculate the power of a number in JavaScript
Beginner · 3 min read
Raising a number to a power means multiplying it by itself a number of times. 2 to the power 10 is 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2, which is 1024. Powers turn up in interest calculations, in areas and volumes, and in computer memory sizes.
JavaScript already has the ** operator for this. In this tutorial you will write your own power(base, exponent) anyway, because building it teaches two useful things: how to handle a zero or negative exponent, and a trick called exponentiation by squaring that does the job in a handful of steps instead of hundreds. You need to know loops, if and what a function is. Recursion is explained as we go.
The words
In 2 ** 10, 2 is the base and 10 is the exponent. Three rules cover the cases this exercise asks about:
- Any number to the power 0 is 1:
5 ** 0is 1. - A negative exponent means "one divided by":
2 ** -3is1 / 2 ** 3, which is0.125. 0 ** 0is also 1 in JavaScript. Mathematicians argue about it; the language simply picks 1.
console.log(2 ** 10); // 1024
console.log(5 ** 0); // 1
console.log(2 ** -3); // 0.125
console.log(0 ** 0); // 1
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
15 Compute b to the power n
easyRaise a base to an exponent, taking both from the caller. Handle a zero and a negative exponent.
Stuck? Three hints, smallest first
- 1. Anything to the power 0 is 1, including
0 ** 0in JavaScript. - 2. A negative exponent is
1 / power(b, -n). - 3. Exponentiation by squaring turns n multiplications into about log2(n).
Step 1: multiply in a loop
The most direct version starts at 1 and multiplies by the base exponent times:
const powerLoop = (base, exponent) => {
if (exponent < 0) return 1 / powerLoop(base, -exponent);
let out = 1;
for (let i = 0; i < exponent; i++) out *= base;
return out;
};
console.log(powerLoop(8, 2)); // 64
console.log(powerLoop(5, 0)); // 1
console.log(powerLoop(2, -3)); // 0.125
An exponent of 0 means the loop never runs, so the answer is the starting value, 1. For a negative exponent, the function calls itself with the positive exponent and divides 1 by the result. A function that calls itself is called recursive.
This works, but 2 to the power 1024 needs 1024 multiplications.
Step 2: the squaring idea
Notice that x ** 8 is (x ** 4) ** 2: work out x ** 4 once, then multiply it by itself. And x ** 4 is (x ** 2) ** 2. Each step halves the exponent. So instead of eight multiplications you need three.
Odd exponents need one extra multiplication: x ** 9 is x ** 4 times x ** 4 times one more x.
Math.floor(exponent / 2) gives the half, rounded down, and exponent % 2 tells you whether there is a leftover:
console.log(Math.floor(9 / 2)); // 4
console.log(9 % 2); // 1, so 9 is odd
console.log(8 % 2); // 0, so 8 is even
Step 3: power by squaring
Now write it recursively. The base case, where the function stops calling itself, is an exponent of 0:
function power(base, exponent) {
if (exponent === 0) return 1;
if (exponent < 0) return 1 / power(base, -exponent);
const half = power(base, Math.floor(exponent / 2));
return exponent % 2 === 0 ? half * half : half * half * base;
}
console.log(power(2, 10)); // 1024
console.log(power(-3, 3)); // -27
console.log(power(-3, 2)); // 9
Follow power(2, 10): it needs power(2, 5), which needs power(2, 2), then power(2, 1), then power(2, 0), which is 1. Coming back up: 1 × 1 × 2 = 2, then 2 × 2 = 4, then 4 × 4 × 2 = 32, then 32 × 32 = 1024.
Negative bases work too: an odd exponent keeps the minus sign, an even one cancels it.
Step 4: count the steps
The full solution counts how many calls it takes to work out 2 to the power 1024:
let steps = 0;
const counted = (b, e) => { steps++; if (e === 0) return 1; const h = counted(b, Math.floor(e / 2)); return e % 2 === 0 ? h * h : h * h * b; };
counted(2, 1024);
console.log(steps); // 12
Twelve calls instead of 1025. Every call halves the exponent: 1024, 512, 256 and so on down to 1, then 0. That is twelve exponents, one call each.
Step 5: fractional exponents
Squaring only works for whole exponents. 9 ** 0.5 is the square root of 9, which is 3, and halving 0.5 never reaches 0. So the answer's first line hands anything that isn't a whole exponent to the built-in operator:
console.log(Number.isInteger(0.5)); // false
console.log(9 ** 0.5); // 3
In the full answer that line is if (!Number.isInteger(exponent)) return base ** exponent;.
In everyday code, just write base ** exponent. The squaring trick matters where numbers are huge, for example in the maths behind encryption, which uses this same method.
The full solution
The panel has power with all its checks, the powerLoop version and the step counter. It prints seven examples, including negative bases and 0 ** 0, and the number of calls for 2 to the power 1024. Press Run to see them.
function power(base, exponent) {
if (!Number.isInteger(exponent)) return base ** exponent; // fall back for fractions
if (exponent === 0) return 1;
if (exponent < 0) return 1 / power(base, -exponent);
// By squaring: x^8 is (x^4)^2, so the exponent halves each step.
const half = power(base, Math.floor(exponent / 2));
return exponent % 2 === 0 ? half * half : half * half * base;
}
// The straightforward loop, for comparison.
const powerLoop = (base, exponent) => {
if (exponent < 0) return 1 / powerLoop(base, -exponent);
let out = 1;
for (let i = 0; i < exponent; i++) out *= base;
return out;
};
let steps = 0;
const counted = (b, e) => { steps++; if (e === 0) return 1; const h = counted(b, Math.floor(e / 2)); return e % 2 === 0 ? h * h : h * h * b; };
counted(2, 1024);
for (const [b, e] of [[8, 2], [2, 10], [5, 0], [2, -3], [-3, 3], [-3, 2], [0, 0]]) {
console.log(`${b} ^ ${e}`.padEnd(9), '=', power(b, e));
}
console.log('calls for 2^1024 by squaring:', steps, 'instead of 1025');
Output
16 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 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("a typical example: 8 squared", power(8, 2), 64);
test('2 to the 10th', power(2, 10), 1024);
test('anything to the 0 is 1', power(5, 0), 1);
test('including 0 to the 0, in JavaScript', power(0, 0), 0 ** 0);
test('to the power 1 is itself', power(9, 1), 9);
test('a negative exponent inverts', power(2, -3), 0.125);
test('a negative base with an odd exponent stays negative', power(-3, 3), -27);
test('and turns positive on an even one', power(-3, 2), 9);
test('0 to a positive power is 0', power(0, 5), 0);
test('1 to any power is 1', power(1, 99), 1);
test('it matches the ** operator', power(2, 20), 2 ** 20);
test('and Math.pow', power(3, 7), Math.pow(3, 7));
test('the loop version agrees', [[8, 2], [2, 10], [5, 0], [2, -3], [-3, 3]].every(([b, e]) => power(b, e) === powerLoop(b, e)), true);
test('squaring needs far fewer steps', steps <= 12, true);
test('rather than one per exponent', steps < 1025 / 50, true);
test('a fractional exponent falls back to **', power(9, 0.5), 3);
Exponentiation by squaring is the content. x^8 is (x^4)^2, so each step halves the exponent and 1025 multiplications become 12 — the assertion checks the count rather than describing it. The exponent % 2 split is the whole mechanism: an even exponent is one squaring of the half, an odd one is that plus a single leftover factor.
In real code write base ** exponent. The pattern still matters, though: modular exponentiation in cryptography is this exact function, where the numbers are far too large to multiply one at a time.
0 ** 0 being 1 is a convention, not a mathematical fact — it is genuinely undefined in analysis, and JavaScript, C and Python all choose 1. The assertion compares against the operator rather than hard-coding it, so it documents the language's choice instead of asserting a truth.
Common mistakes
- Starting the result at 0. Anything multiplied by 0 stays 0. Start at 1.
- Forgetting negative exponents. A plain loop with
i < exponentnever runs for-3and wrongly returns 1. - Calling
power(base, exponent / 2)withoutMath.floor. For an odd exponent you get a fraction, and the recursion never reaches 0.
Try it yourself
- Use
powerto check thatpower(2, 20) === 2 ** 20. - Add a counter to
powerLoopand compare it withpowerfor an exponent of 100. - Write
isPowerOfTwo(n)using a loop that keeps dividing by 2.