Emmanuel Akinfulubi

JavaScriptMath

Calculate the nth root of a number in JavaScript

Intermediate · 4 min read

JavaScript has Math.sqrt for square roots and Math.cbrt for cube roots, but nothing for a 4th, 5th or 10th root. The nth root of x is the number that, multiplied by itself n times, gives x. The 4th root of 81 is 3, because 3 times 3 times 3 times 3 is 81. You need these for growth rates (the average yearly growth over 5 years is a 5th root) and for geometry.

In this tutorial you will write nthRoot(x, n). The plain formula fails for negative numbers, so you will fix it: the 5th root of -32 should be -2, while the 4th root of -16 should stay NaN, because no real number qualifies. You need to know **, Math.abs and %.

Roots as powers

The nth root of x is x raised to the power 1 / n. A square root is the power one half, a cube root the power one third:

JavaScript

console.log(81 ** (1 / 4)); // 3

Odd and even roots of negatives

  • An odd root (3rd, 5th, 7th) of a negative number exists. -2 times itself 5 times is -32, because an odd number of minus signs leaves a minus.
  • An even root (2nd, 4th) of a negative number has no real answer. Any number multiplied by itself an even number of times is positive or zero.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

29 An nth root that handles negatives

fair

Write nthRoot(x, n). It must give -2 for the 5th root of -32, and NaN for the 4th root of -16, since no real number qualifies.

Stuck? Three hints, smallest first
  1. 1. x ** (1 / n) is the base case, and it fails for every negative x.
  2. 2. An odd root of a negative exists: take the root of the magnitude and put the sign back.
  3. 3. An even root of a negative has no real value, so let it stay NaN.

Step 1: the plain formula

Step 1

const nthRootTry = (x, n) => x ** (1 / n);
console.log(nthRootTry(27, 3)); // 3
console.log(nthRootTry(81, 4)); // 3
console.log(nthRootTry(-32, 5)); // NaN, but the answer is -2

Positive numbers work. The negative one fails because ** refuses a negative base with a fractional exponent. 1 / 5 is 0.2, a fraction, so you get NaN.

Step 2: take the root of the size, then put the sign back

For an odd root of a negative, work with the size of the number and add the minus sign at the end. Math.abs(-32) is 32. The 5th root of 32 is 2. Put the minus back, and you get -2.

Step 2

console.log(Math.abs(-32) ** (1 / 5));    // 2
console.log(-(Math.abs(-32) ** (1 / 5))); // -2

The brackets around the power are required. JavaScript doesn't allow a minus sign directly in front of a ** expression. Writing -Math.abs(x) ** (1 / n) is a syntax error, so the code won't run. In node the message is "'**' cannot be applied to unary/await expression."

Step 3: only for odd roots

You only want the sign trick when n is odd. Test that with Math.abs(n % 2) === 1. The Math.abs is there because % keeps the sign of the left-hand number.

Step 3

function nthRoot(x, n) {
  if (x < 0 && Math.abs(n % 2) === 1) return -(Math.abs(x) ** (1 / n));
  return x ** (1 / n);
}
console.log(nthRoot(-32, 5)); // -2
console.log(nthRoot(-16, 4)); // NaN
console.log(nthRoot(7, 1));   // 7

When x is negative and n is even, the function falls through to the plain formula, which gives NaN. That is what we want: there is no real 4th root of -16, and NaN says so. Hiding it with a made-up number would be worse.

Step 4: an accuracy surprise

Now try the cube root of 1000, which is exactly 10:

Step 4

console.log(nthRoot(1000, 3)); // 9.999999999999998
console.log(Math.cbrt(1000));  // 10

The problem is the exponent. 1 / 3 can't be stored exactly. It is 0.333... cut off after about 16 digits, so the power is a tiny bit too small, and so is the answer. Math.cbrt uses a method built just for cube roots, so it gets 10 exactly.

The general rule: when a root has its own function (Math.sqrt, Math.cbrt), that function is more accurate than building it from **.

Step 5: compare after rounding

Since general roots are rarely exact, round them before you compare. This helper rounds to 10 decimal places:

Step 5

const round = (v, places = 10) => Math.round(v * 10 ** places) / 10 ** places;
console.log(round(nthRoot(1000, 3))); // 10
console.log(round(nthRoot(1000, 3)) === 10); // true

It moves the decimal point 10 places right, rounds to a whole number, then moves it back. places = 10 is a default value, used when you don't pass a second argument.

The full solution

The answer panel defines nthRoot and round, prints the 3rd and 4th roots, both negative cases and the 1000 comparison. The checks underneath confirm each one, including that the plain formula gives NaN for -32 and that Math.cbrt(1000) is exactly 10. Press Run to see the output.

The answer

function nthRoot(x, n) {
  if (x < 0 && Math.abs(n % 2) === 1) return -(Math.abs(x) ** (1 / n));
  return x ** (1 / n);
}

// Roots are rarely exact, so compare after rounding.
const round = (v, places = 10) => Math.round(v * 10 ** places) / 10 ** places;

console.log('nthRoot(27, 3)  :', nthRoot(27, 3));
console.log('nthRoot(81, 4)  :', nthRoot(81, 4));
console.log('nthRoot(-32, 5) :', nthRoot(-32, 5));
console.log('plain expression:', (-32) ** (1 / 5), '<- NaN');
console.log('nthRoot(-16, 4) :', nthRoot(-16, 4), '<- correctly no real answer');
console.log('nthRoot(1000, 3):', nthRoot(1000, 3), 'against Math.cbrt:', Math.cbrt(1000));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the cube root of 27', nthRoot(27, 3), 3);
test('the 4th root of 81', nthRoot(81, 4), 3);
test('an odd root of a negative is negative', nthRoot(-32, 5), -2);
test('where the plain expression gives NaN', Number.isNaN((-32) ** (1 / 5)), true);
test('an even root of a negative has no real answer', Number.isNaN(nthRoot(-16, 4)), true);
test('the 1st root is the number itself', nthRoot(7, 1), 7);
test('the general form is less accurate than cbrt', nthRoot(1000, 3), 9.999999999999998);
test('so round before comparing', round(nthRoot(1000, 3)), 10);
test('while cbrt gets it exactly', Math.cbrt(1000), 10);

Two things to carry. First, -(Math.abs(x) ** (1 / n)) needs its brackets: -Math.abs(x) ** (1 / n) is a syntax error, because the language refuses to guess whether the unary minus binds before or after **.

Second, the accuracy assertion. 1000 ** (1/3) is 9.999999999999998 because 1/3 is not a third, so the exponent itself is already approximate. Math.cbrt uses a dedicated algorithm and returns exactly 10. Wherever a specific root has its own function — sqrt, cbrt, hypot, log2, log10 — that function is more accurate than building it from ** or log.

Common mistakes

  • Using x ** (1 / n) for every input. It gives NaN for any negative x, even when a real odd root exists.
  • Leaving out the brackets in -(Math.abs(x) ** (1 / n)). Without them the code is a syntax error.
  • Comparing roots with ===. nthRoot(1000, 3) is 9.999999999999998. Round first, or use Math.cbrt when you can.

Try it yourself

  1. A savings account grew from 1000 to 1610.51 naira over 5 years. Find the yearly growth factor with nthRoot(1610.51 / 1000, 5), rounded to 4 places.
  2. Find the 7th root of -128. What should it be?
  3. Change nthRoot so it returns NaN when n is 0 or not a whole number.

Keep practising

Newsletter

New writing, when it lands.

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