JavaScript Math.sqrt() Method



The Math.sqrt() method in JavaScript accepts a numeric value as its argument and returns the square root of that number (non-negative number). Mathematically, if x is the number passed to Math.sqrt(x), the result is the non-negative number y such that y * y = x. If the provided argument is less than 0 or string characters, it returns NaN (Not a number) as result. If 0 or -0 is provided, 0 will be the result.

This method is commonly used to calculate the square root of a given numerical expression.

Syntax

Following is the syntax of JavaScript Math.sqrt() method −

Math.sqrt(x)

Parameters

This method accepts only one parameter. The same is described below −

  • x: A numeric value.

Return value

This method returns the square root of the provided number.

Example 1

Following is the basic example of JavaScript Math.sqrt() method −

<html>
<body>
<script>
   let result = Math.sqrt(25);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, the Math.sqrt() method returns the square root of 25 as "5".

Example 2

Here, we are providing a decimal number as an argument to the Math.sqrt() method −

<html>
<body>
<script>
   let result = Math.sqrt(8.64);
   document.write(result);
</script>
</body>
</html>

Output

It returns approximately "2.939387691339814" as result.

Example 3

If the provided argument is 0 or -0, this method will return 0 as result −

<html>
<body>
<script>
   let result1 = Math.sqrt(0);
   let result2 = Math.sqrt(-0);
   document.write(result1, "
", result2); </script> </body> </html>

Output

As we can see the output, 0 is returned as a result.

Example 4

If we provide a negative number to this method, it returns NaN as result −

<html>
<body>
<script>
   let result = Math.sqrt(-34);
   document.write(result);
</script>
</body>
</html>

Output

As we can see in the output, NaN is returned as result.

Example 5

If string characters are provided as an argument, it returns NaN as result −

<html>
<body>
<script>
   let result = Math.sqrt("Tutorialspoint");
   document.write(result);
</script>
</body>
</html>

Output

As we can see in the output, NaN is returned as result.

Advertisements