Design & Download
Your JS Library
in Seconds!!!

Snippet: nthRoot()

Written by Christopher West (cwest) on November 17, 2015.
Finds the nth root of a number.
function nthRoot(root, x) {
  try {
    var negate = root % 2 == 1 && x < 0;
    if(negate)
      x = -x;
    var possible = Math.pow(x, 1 / root);
    root = Math.pow(possible, root);
    if(Math.abs(x - root) < 1 && (x > 0 == root > 0))
      return negate ? -possible : possible;
  } catch(e){}
}

In JS we can easily find the square-root of a number by using Math.sqrt(number). On the other hand, finding the nth-root of a number can be a bit more challenging unless you use a library like YourJS. For instance if we wanted to find the 5th-root of 243 we could use YourJS.nthRoot() as shown below:

console.log(YourJS.nthRoot(5, 243));
// -> 3

nthRoot(...) API Documentation

Parameters

  1. root {number}:
    The amount to which the number should be rooted. Eg. for square-root you would pass in 2.
  2. x {number}:
    The number that should be rooted. Eg. for square-root of 81, 81 would be passed in here.

Returns

Returns the the equivalent of x1/root.