Recently started learning Javascript.
Given an assignment for my class, to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, wrote code like this:
function myFunction(num) {
var p = document.getElementById("mydata");
for (var i = 0; i <= num; i++) {
sum = sum + i;
p.innerHTML = "Result = " + sum;
}
}
After submitting assignment for school, learned that had to add var sum = 0
above var p = document.getElementById("mydata")
However, do not understand what var sum = 0
means. As for looks already show when to begin and end calculating, feel like it doesn't have to be there.
var sum = 0;
declares a local variable named sum
, and sets its initial value to 0
.
If you don't do this, when you do:
sum = sum + i;
the variable sum
is initially undefined, and adding i
to it results in NaN
(Not a Number).
Some languages (e.g. PHP) automatically treat initialized variables as 0
in arithmetic expressions, but JavaScript doesn't do this, so you need to specify the initial value of the variable.
This has nothing to do with the way the for
loop determines when to begin and end. It's about how to correctly add the numbers along the way.
It doesn't have to be before the p
assignment, but it needs to be before the for
loop.
Also, the line
p.innerHTML = "Result = " + sum;
doesn't need to be inside the loop. You should wait until the loop is done.