/  Technology   /  Calculate the square root of a number in JavaScript

Calculate the square root of a number in JavaScript


Using JavaScript we can calculate the square root of a number by using Math.sqrt() method. This method returns the square root of a number. If the value of a number is negative, sqrt returns NaN(Not a Number).

     <title>Calculate the square root of a number in JS</title>
         var res = Math.sqrt( 30 );
         document.write("First value : " + res + "<br />");
         var res = Math.sqrt( 16 );
         document.write("Second value : " + res );


In the above code, we have created an  html document and giving javascript logic in scripting tag.

We have declared a variable called res which uses the Math.sqrt() method of javascript to return the soiree root of any number. In the parameter we pass any valid number to get its square root. Here we have given 30. Using the document.write method it displays whatever want return on the window. In document.write() we are passing “First value” concatinated with the res variable and also added some break. The concatinated value returns “First value “ : 5.47. As  5.47 is the square root of 30.

Similarly we have taken square root of 16 which returns 4.

Here is the relevant output for the above code.



Leave a comment