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
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:
Math.sqrt(#)
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 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 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