3. Loop
Recall during your previous programming lessons that there are tasks that are executed repetitively, such as printing numbers in a specific range and iterating through an array. Instead of coding a line for each item, loops can be used to give instructions to the program to do an action repeatedly until a condition is met.
There are different kinds of loops depending on the structure and we will discuss only one here which is the for loop other loop structures will be taken in the fourth quarter.
The code below is an example of a for loop:
The start statement defines the base case, or the starting of the loop and is executed once before the code block is executed. The condition statement defines the conditions on which to run the loop. After the code block has been executed, the increment statement is executed.
All three statements in the definition of a for loop are optional. You may opt to remove one, two, or even all three of the statements in defining a for loop. Just make sure though that a break statement is present inside the loop to avoid infinite loops and that at least one variable is changing for every cycle so that the condition for the break statement will become true.
Given below is an example of how to use for loops. The example accepts a number and returns the sum of all integers from 1 to the given number.
<script>
sum = 0; a = 4
for(i=0; i<=a; i++){
sum = sum + i;
}
window.alert(sum);
</script>
`
There are more loops that are available in JavaScript. You will learn more about loops in in the succeeding lessons. For now, the for..loop structure introduced in this lesson is enough to help you solve programming problems and implement website features using JavaScript for this quarter.