DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Updated on • Originally published at flexiple.com

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

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.

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

Table of Contents - JavaScript Square Root:

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 Javascript Square root function:

Math.sqrt(#)
Enter fullscreen mode Exit fullscreen mode

Parameters:

"#" - 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 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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

JavaScript Sqaure 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

Oldest comments (3)

Collapse
 
kakarlus profile image
kakarlus

nah

Collapse
 
camelcaseguy profile image
Shubhendra Singh Chauhan

I guess you made a typo: NaH NaN

Collapse
 
hrishikesh1990 profile image
hrishikesh1990

Hey Shubhendra, my bad, thank you for pointing it out. :))