EN
JavaScript - Math.sqrt() method example
16 points
Math
sqrt
is a static method that returns a number which is the square root of an input value. The method works only on positive real numbers.
xxxxxxxxxx
1
console.log( Math.sqrt( 4 ) ); // 2
2
console.log( Math.sqrt( 9 ) ); // 3
3
4
console.log( Math.sqrt( 2 ) ); // 1.4142135623730951
5
console.log( Math.sqrt( 0.5 ) ); // 0.7071067811865476
6
console.log( Math.sqrt( 0 ) ); // 0
7
console.log( Math.sqrt( -1 ) ); // NaN
Syntax | Math.sqrt(number) |
Parameters | number - integer or float number value in the range 0 to +Infinity (primitive value). |
Result |
Square root If the operation can not be executed |
Description | sqrt is a static method that returns a number which is the square root of the input value. The method works only on positive real numbers. |
In this example, the way how to calculate square root using the power function is presented.
xxxxxxxxxx
1
function calculateSqrt(value) {
2
return Math.pow(value, 0.5);
3
}
4
5
6
// Usage examples:
7
8
console.log( calculateSqrt( 4 ) ); // 2
9
console.log( calculateSqrt( 9 ) ); // 3
10
11
console.log( calculateSqrt( 2 ) ); // 1.4142135623730951
12
console.log( calculateSqrt( 0.5 ) ); // 0.7071067811865476
13
console.log( calculateSqrt( 0 ) ); // 0
14
console.log( calculateSqrt( -1 ) ); // NaN