How to get the Square root of a number using Javascript?


In this short tutorial, we look at how users can find the square root of a number using javascript. we also look into the various edge cases that would help you gain a holistic understanding of the concept.

Table of Contents

Syntax & Explanation of Javascript Square root:

Square root is one of the many arithmetic operations that javascript supports. To achieve this, javascript uses theMath.sqrt() function under the Math method and since sqrt() a static method of Math it must be used as Math.sqrt().

Syntax of Javascript Square root function:



# - A number or an array storing a number.

Return Value:

The square root of the parameter. Sqrt() returns NaH is few cases we discuss them later in the tutorial.

Sample code with explanation of sqrt():

Once you have understood the syntax of the square root function in javascript the code would seem pretty straightforward. And in case you are already experienced in other programming languages, you would notice that it's quite similar.

// Output: 5

//output: 0.5

Or in case you are looking to write it to your webpage:

<!DOCTYPE html>
        <p id="squareroot"></p>
            document.getElementById("squareroot").innerHTML = Math.sqrt(25);

We are passing the value within the function and the square root is returned.

Limitations and Caveats

The sqrt() function in javascript has quite a few limitation and caveats, I've listed them below.
  • When a negative number is passed as a parameter the function return NaH
  • Arrays with one number work fine, however, for instances where an array contains more than one number NaH is returned. A method to overcome this is to create a function that runs square root in the value individually and then return it
  • Strings and empty parameters also return NaH when passed
  • And lastly, empty arrays return 0