Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
JavaScript Math.sqrt()
In this tutorial, you will learn about the JavaScript Math.sqrt() method with the help of examples.
The sqrt() method computes the square root of a specified number and returns it.
Example
// square root of 4
let number = Math.sqrt(4);
console.log(number);
// Output: 2
sqrt() Syntax
The syntax of the Math.sqrt() method is:
Math.sqrt(number)
Here, sqrt() is a static method. Hence, we are accessing the method using the class name, Math.
sqrt() Parameter
The sqrt() method takes a single parameter:
number- value whose square root is to be calculated
sqrt() Return Value
The sqrt() method returns:
- the square root of a given positive integer or decimal
number - NaN (Not a Number) if the argument is non-numeric or negative
Example 1: JavaScript Math.sqrt()
// sqrt() with integer number
let number1 = Math.sqrt(16);
console.log(number1);
// sqrt() with a floating number
let number2 = Math.sqrt(144.64);
console.log(number2);
// Output:
// 4
// 12.026637102698325
Here, we have used the Math.sqrt() method to compute the square root of an integer value, 16 and a decimal value, 144.64.
Example 2: sqrt() with Negative Argument
// sqrt() with negative number
let number = Math.sqrt(-324);
console.log(number);
// Output: NaN
Mathematically, the square root of any negative number is an imaginary number. That is why the sqrt() method returns NaN as the output.
Example 3: sqrt() with Infinity Values
// sqrt() with positive infinity
let number1 = Math.sqrt(Infinity);
console.log(number1);
// Output: Infinity
// sqrt() with negative infinity
let number2 = Math.sqrt(-Infinity);
console.log(number2);
// Output: NaN
Example 4: sqrt() with Numeric String
// cbrt() with a decimal number
let number1 = Math.cbrt("81");
console.log(number1);
// Output: 4.326748710922225
In the above example, the Math.sqrt() method converts the numeric string "81" into a number and then computes its square root.
Example 5: sqrt() with Non-Numeric Argument
let string = "Harry";
// sqrt() with string as argument
let number = Math.sqrt(string);
console.log(number);
// Output: NaN
In the above example, we have tried to calculate the square root of the string "Harry". That's why we get NaN as the output.
Also Read: