You use for when you want that a code block repeat n times.
<html>
<body>
<script>
a = 2
for (i = 0; i < 2; i++)
{
a = i
}
alert(a)
</script>
</body>
</html>
There is something new, the like with the red background. Let's analyze-it.
for (i = 0; i < 2; i++)
We will be using a temporary variable called
i. We will begin with its value equal to zero.
for (i = 0; i < 2; i++)
The middle block works like a
if. In this case, if
i is lower than 2, it will enter the loop.
for (i = 0; i < 2; i++)
The last part tell us what to do with the
i variable. In this case, each time the code is looped, we increment by 1 the value of
i. If we wouldn't do that, the conditional (
i < 2) would always be true, and we would enter in an infinite loop, because the value of
i would always be less than 2.