I tried making a simple program using javascript which will calculate the sum and average of two numbers entered in the textfields.
<script>
var a=parseInt(document.getElementById("text1").value);
var b=parseInt(document.getElementById("text2").value);
function sum()
{
var result = document.getElementById("valueofsum");
var sum=a+b;
result.innerHTML = sum;
}
function average()
{
var result = document.getElementById("valueofavg");
var avg=(a+b)/2;
result.innerHTML = avg;
}
function reset()
{
document.getElementById("text1").value = "";
document.getElementById("text2").value = "";
document.getElementById("valueofsum").innerHTML = "";
document.getElementById("valueofavg").innerHTML = "";
}
</script>
The two variables which reads the values from textfields are globally declared and initialized as "a" and "b". The sum and average are returned as NaN(NotaNumber) instead of the calculated results.
If i use/declare both the variables inside the functions as local variables the code seems out to be working properly which makes me wonder about the scope of global variables in javascript?
console.log(a); console.log(b);and guess why they areNaN?setInterval(), that fetches the values and prints them continually.