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
<html>
<head>
<title>Error_handling</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
</body>
</html>
and here is that script.js file,
window.onload = initAll;
function initAll() {
var ans = prompt("Enter a number","");
try{
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) {
alert(errMsg.message);
}
}
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".