JavaScript Math.sqrt()
Syntax & Examples


Math.sqrt() static-method

The Math.sqrt() static method in JavaScript returns the positive square root of a number. If the number is negative, it returns NaN.


Syntax of Math.sqrt()

The syntax of Math.sqrt() static-method is:

Math.sqrt(x)

This sqrt() static-method of Math returns the positive square root of the given number x. If x is negative, returns NaN.

Parameters

ParameterOptional/RequiredDescription
xrequiredA number whose positive square root is to be calculated. If the number is negative, the result is NaN.

Return Type

Math.sqrt() returns value of type Number.



✐ Examples

1 Using Math.sqrt() with a positive number

In JavaScript, we can use the Math.sqrt() method to calculate the positive square root of a positive number.

For example,

  1. We pass the number 9 to the Math.sqrt() method.
  2. The result, 3, is the positive square root of 9.
  3. We log the result to the console using the console.log() method.

JavaScript Program

const result = Math.sqrt(9);
console.log(result);

Output

3

2 Using Math.sqrt() with zero

In JavaScript, we can use the Math.sqrt() method to calculate the square root of zero.

For example,

  1. We pass the number 0 to the Math.sqrt() method.
  2. The result, 0, is the square root of zero.
  3. We log the result to the console using the console.log() method.

JavaScript Program

const result = Math.sqrt(0);
console.log(result);

Output

0

3 Using Math.sqrt() with a negative number

In JavaScript, we can use the Math.sqrt() method to attempt to calculate the square root of a negative number, which will result in NaN.

For example,

  1. We pass the number -1 to the Math.sqrt() method.
  2. The result, NaN, indicates that the square root of a negative number is not a real number.
  3. We log the result to the console using the console.log() method.

JavaScript Program

const result = Math.sqrt(-1);
console.log(result);

Output

NaN

Summary

In this JavaScript tutorial, we learned about sqrt() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.