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


Introduction

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:

Math.sqrt(#)

Parameters:

# - 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.

console.log(Math.sqrt(25));
// Output: 5

console.log(Math.sqrt(0.25));
//output: 0.5

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

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

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