My FeedDiscussionsHeadless
Sign in
Log inSign up

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

Learn how to find the square root of a number using sqrt() in Javascript

Karthik Sridharan's photo
Karthik Sridharan
·May 6, 2021·

2 min read

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.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Content:

  • Syntax & Explanation of Javascript Square root
  • Sample code with explanation of sqrt()
  • Limitations and Caveats

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 NaN in few cases we discuss 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 limitations and caveats, I've listed them below.

  • When a negative number is passed as a parameter the function return NaN
  • Arrays with one number work fine, however, for instances where an array contains more than one number NaN 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 NaN when passed
  • And lastly, empty arrays return 0