JavaScript Square Root - All you need to know


In this short tutorial, we look at how you could use the JavaScript square root method to find the square root of a number.

We also look into the various edge cases that would help you gain a holistic understanding of the concept.

Table of Contents - JavaScript Square root

  • Syntax & Explanation of JavaScript Square root
  • Sqrt() Code with Explanation
  • JavaScript square root: Limitations and Caveats
  • Other Related Concepts

Syntax & Explanation of JavaScript Square root:

The square root is one of the many arithmetic operations that the language supports.

To achieve this, JavaScript uses the Math.sqrt() function under the Math method.

Syntax of Sqrt() function:



# - A number or an array storing a number.

Return Value:

The Sqrt() returns the square root of the parameter.
The Sqrt() returns NaN in a few cases. We discuss them later in the tutorial.

Sqrt() Code with Explanation:

Once you have understood the syntax of the square root function 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

In case you are looking to write it to your webpage:
<!DOCTYPE html>
        <p id="squareroot"></p>
            document.getElementById("square root").innerHTML = Math.sqrt(25);

In this code block, we are passing the value within the function and the square root is returned.

JavaScript square root: Limitations and Caveats

The sqrt() function in JavaScript has quite a few limitations and caveats, I've listed them all below.
  • When a negative value is passed as a parameter the function return NaN
  • Arrays with one number work fine, however, for an array containing more than one number NaN is returned. A method to overcome this is to create a function that loops over the values and runs square root in the value individually.
  • Strings and empty parameters also return NaN when passed
  • And lastly, empty arrays return 0