This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Content:
- Sample code with explanation of sqrt()
- Limitations and Caveats
Math.sqrt() function under the Math method, and since
sqrt() a static method of Math it must be used as
"#" - A number or an array storing a number.
The square root of the parameter. Sqrt() returns NaN in few cases we discuss later in the tutorial.
Sample code with explanation of sqrt():
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:
<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
- When a negative number is passed as a parameter the function return
- Arrays with one number work fine, however, for instances where an array contains more than one number
NaNis 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
- And lastly, empty arrays return 0