The Math.sqrt()
method in JavaScript is used to calculate the square root of a non-negative number.
Syntax
Math.sqrt(x);
Parameters
- x (Required): A number representing the value for which you want to compute the square root. This number must be non-negative because the square root of negative numbers is not a real number (it could be a complex number). If the argument is negative, the result will be NaN (Not-a-Number).
Return Value
- Positive Number: If
x
is a non-negative number,Math.sqrt(x)
returns the square root ofx
. - NaN: If
x
is negative, the method returns NaN (Not-a-Number), because square roots of negative numbers are not real numbers in the realm of real-number arithmetic.
Example 1: Basic example to use Math.sqrt() to get the square root of a number.
let result = Math.sqrt(9); console.log(result); // Output: 3 result = Math.sqrt(0); console.log(result); // Output: 0 result = Math.sqrt(1); console.log(result); // Output: 1
Example 2: Square root of Negative Input
let result = Math.sqrt(-4); console.log(result); // Output: NaN
In this case, the argument is negative, so Math.sqrt()
returns NaN
because the square root of a negative number is not a real number.
Example 3: Square Root of a Large Number
let result = Math.sqrt(1000000); console.log(result); // Output: 1000
The square root of 1,000,000 is 1,000.
Example 4: Square Root of Infinity
let result = Math.sqrt(Infinity); console.log(result); // Output: Infinity
The square root of Infinity
is still Infinity
.
Example 5: Using Variables with Math.sqrt()
let x = 16; let result = Math.sqrt(x); console.log(result); // Output: 4
You can pass variables to Math.sqrt()
as well. In this case, the square root of 16 is 4.
Supported Browsers
Browser | Version Supported |
---|---|
Chrome | 1.0+ |
Firefox | 1.0+ |
Safari | 1.0+ |
Edge | 12+ |
Internet Explorer | 6+ |
Opera | 7.0+ |