JavaScript Math sqrt (with Example)

In this tutorial, you will learn about the javascript math sqrt() method with the help of multiple examples.

The Math.sqrt() method returns the square root of a specified number.

Example

// square root of 4
let a = 4;
let result = Math.sqrt(a);
console.log(result);
// Output : 2

Math.sqrt() Syntax

The syntax of Math.sqrt() method is:

Here, sqrt() is a static method of Math, So it is always used as Math.sqrt(). Here Math is the class name.

Math.sqrt() Parameter

number: it is a number whose square root you want to calculate. It must be greater than or equal to 0.

Math.sqrt() Return Value

Math.sqrt() returns:

the square root of a given decimal or positive number.
If the argument is non-numeric or negative then it returns NaN (Not a Number).

Example 1: Javascript Math.sqrt()

// with integer number
let number1 = Math.sqrt(4);
console.log(number1);
// Output: 2

// with a floating number
let number2 = Math.sqrt(16.4);
console.log(number2);
// Output: 4.049691346263317

Here, we have used Math.sqrt() method to find the square root of integer value 4 and decimal value 16.4.

Example 2: Math.sqrt() with Negative Argument

// with a negative argument
let result = Math.sqrt(-4);
console.log(result);
// Output: NaN

If we try to find the square root of a negative number using Math.sqrt(), we will get NaN (Not a Number) as a result.

Example 3: Math.sqrt() with Non-Numeric Argument

// with the non-numeric argument
let result = Math.sqrt("hello");
console.log(result);
// Output: NaN

If we try to find the square root of a non-numeric number, we will get NaN (Not a Number) as a result.

Example 4: Math.sqrt() with Numeric String

// with the numeric string
let result = Math.sqrt("4");
console.log(result);
// Output: 2

In the above program, “4” is a numeric value of string type. In this situation, Math.sqrt() will first convert the numeric string into a number and then it will return the square root of it.

Example 5: Math.sqrt() with Infinity Values

// with infinity values
let result = Math.sqrt(Infinity);
console.log(result);
// Output: Infinity

Leave a Comment

Your email address will not be published. Required fields are marked *