In JavaScript, to get the square root of a number we use the Math.sqrt() method.

var num = Math.sqrt(9);

The above code would return the number 3.

Some other examples of Math.sqrt() are below:

var num = Math.sqrt(1);
var num1 = Math.sqrt(0);
var num2 = Math.sqrt(10);
var num3 = Math.sqrt(196);
var num4 = Math.sqrt(31.3);
var num5 = Math.sqrt(-50);

Which would result in the following:

1
0
3.1622776601683795
14
5.594640292279746
NaN

JavaScript Square Root in action using jQuery

Below we will provide code to let the user input a number, and then use the Math.sqrt() method to find the square root of that number. Here is our simple HTML setup:

Type a number you want to use the Math.sqrt() method on below:

Below is the JavaScript and jQuery code which take the user input using the jQuery click() or on() keypress methods, and use the Math.sqrt() method on that user input and update the results below using the jQuery text() method.

$('#userVal').on('keypress',function(e) {
  if(e.which == 13) {
    $("#results").text(Math.sqrt($("#userVal").val()));
  }
});
$("#submitNum").click(function(){
  $("#results").text(Math.sqrt($("#userVal").val()));
});

The final code and output for this example is below:

Code Output:

Type a number you want to use the Math.sqrt() method on below:


Full Code:

Type a number you want to use the Math.sqrt() method on below:

<script> $('#userVal').on('keypress',function(e) { if(e.which == 13) { $("#results").text(Math.sqrt($("#userVal").val())); } }); $("#submitNum").click(function(){ $("#results").text(Math.sqrt($("#userVal").val())); }); </script>

Hopefully this article has been useful in helping you understand how to find the square root of a number in JavaScript.

Categorized in:

JavaScript,

Last Update: February 26, 2024