It is often necessary to repeat certain blocks of code for a specified(or unspecified) number of times. We use a control structure known as a loop to accomplish this. Every loop has four basic parts:
Loop control variable declaration/initialization
Loop condition
Control variable alteration/reassignment
Loop body(statements to be repeated)
Loops come in two basic varieties:
PreTest: The condition is tested before the loop execute. This means that if the condition fails, the code in the loop may never execute.
PostTest: The condition is tested after the loop code runs. The code will always run at least once.
Regardless of whether you loop is pre or post test, it also has another type of classification: counting or sentinal. Counting loops are set to execute a certain number of times. Loops that depend on user input are called sentinal loops, and will execute as many times as necessary until the user enters a predefined value.
JavaScript also has two loop keywords that can help control the flow of the loop. Those words are
break
and
continue
. Break will immediately send control to the code following the loop. Continue sends control immediately to the top of the loop.
For Loops
A for loop, like any loop has 4 parts: the loop control variable start value, condition, code to be executed and an alteration of the control variable. “for” loops are popular because the combine 3 of these four items into one line. Here is an example of a for loop:
for(let x=0; x<5; x+=1){
//code
}
This is read, for the variable x starting with a value of 0 and as long as x is less than 5, execute the code and increment x by 1 each time.