totn JavaScript

JavaScript: Math sqrt() function

This JavaScript tutorial explains how to use the math function called sqrt() with syntax and examples.

Description

In JavaScript, sqrt() is a function that is used to return the square root of a number. Because the sqrt() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the sqrt() function is:

Math.sqrt(number);

Parameters or Arguments

number
The number used to calculate the square root. The number must not be a value that is greater than or equal to 0.

Returns

The sqrt() function returns the square root of a number.

If the number is a negative number, the sqrt() function will return NaN.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which sqrt() is one of these functions.

Example

Let's take a look at an example of how to use the sqrt() function in JavaScript.

For example:

console.log(Math.sqrt(25));
console.log(Math.sqrt(3));
console.log(Math.sqrt(-9));

In this example, we have invoked the sqrt() function using the Math class.

We have written the output of the sqrt() function to the web browser console log, for demonstration purposes, to show what the sqrt() function returns.

The following will be output to the web browser console log:

5
1.7320508075688772
NaN

In this example, the first output to the console log returned 5 which is the square root of 25.

The second output to the console log returned 1.7320508075688772 which is the square root of 3.

The third output to the console log returned NaN since the value -9 is a negative number.