The sqrt method in JavaScript is utilized to compute the square root of a specified number. In cases where the input number is negative, the method will yield NaN (Not a Number).
Syntax
The method sqrt follows this syntax:
Example
Math.sqrt(num)
Parameter
num - A number.
Return
The square root of the given number.
JavaScript Math sqrt method example
In this section, we will explore the sqrt function by examining several examples.
Example 1
Let us examine a scenario where we calculate and display the square root of specified numbers.
Example
<script>
document.writeln(Math.sqrt(16)+ "<br>");
document.writeln(Math.sqrt(12));
</script>
Output:
Output
4
3.4641016151377544
Example 2
Let’s explore instances when the sqrt function yields NaN.
Example
<script>
document.writeln(Math.sqrt()+ "<br>");
document.writeln(Math.sqrt(-9));
</script>
Output:
Output
NaN
NaN
Example 3
In this section, you have the opportunity to evaluate the sqrt function by creating and executing your own test cases.
Example
<script>
function display()
{
var x=document.getElementById("num").value;
document.getElementById("result").innerHTML=Math.sqrt(x);
}
</script>
<form>
Enter a number: <input type="text" id="num">
<input type="button" onclick="display()" value="submit">
</form>
<p><span id="result"></span></p>