JavaScript Math sqrt() method - JavaScript Tutorial

JavaScript Math sqrt() method

BLUF: This tutorial on JavaScript Math sqrt() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Math sqrt() method

Understanding JavaScript Math sqrt() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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>

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience