Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Find the Nth root of a number using the Math.pow() method.
Math.pow() static method returns the value of a base raised to a power.
Math.pow(x, y) = xy
Math.pow(2, 2) 22 2 × 2 → 4
Math.pow(2, 3) 23 2 × 2 × 2 → 8
Math.pow(3, 3) 33 3 × 3 × 3 → 27
Math.pow(3, 4) 34 3 × 3 × 3 × 3 → 81
Math.pow() is equivalent to the exponent operator ** except Math.pow() only accepts numbers.
Initialize a variable to hold the root value.
const num1 = 2; → user input
Initialize a variable to hold the number whose root is to be found.
const num2 = 81; → user input
Define a function findRoot to find the root of a number.
function findRoot(str) {}
The function takes two numbers as input num1, num2 representing the root and the number whose root is to be found.
num1 → root
num2 → number
A negative root (exponent) results in the reciprocal of the base raised to the positive exponent.
A negative base with a fractional root (exponent) can lead to NaN in JavaScript, as it does not handle complex numbers.
Check if the root is a negative number.
if (root <= 0) {}
If true, throw an error.
throw new Error("The root must be a positive number.")
If root is positive number, calculate and return the root using Math.pow
return Math.pow(num, 1 / root) Returns the root of the number
Call the function with ↴
findRoot(num1, num2);
Find the Nth root of a number.
2√81 → find square root of 81
const num1 = 2;
const num2 = 81;
function findRoot(root, num) {
if (root <= 0) {
throw new Error("The root must be a positive number.");
}
return Math.pow(num, 1 / root);
}
call function
findRoot(num1, num2); returns ↴
9
Alternative to find the square root of a number using built-in Math.sqrt() method ↴
Math.sqrt(81); returns ↴
9