Tuesday, 12 June 2012

Calculating sqrt in javascript

How to calculate square root of a number in javascript ?

here is the code to calculate square root of a number in javascript,
after taking input from the user,

here is the html file, nothing fancy here,
since all the cool thng is gonna happen in the javascript file, script.js

<script type="text/javascript" src="script.js"> 

and here is that script.js file,

window.onload = initAll;                                              

function initAll() {                                                  
var ans = prompt("Enter a number","");                            
if (!ans || isNaN(ans) || ans<0) {                            
throw new Error("Not a valid number");                    
alert("The square root of " + ans + "is " + Math.sqrt(ans));    
catch (errMsg) {                                                  

this prompts the user to type in a number he/she wants to calculate the square root of ,
and then is that input isn't a number or is a negative number or nothing at all,
then a error message is displayed , that "not a valid number".
Post a Comment