A loop is a programming tool that repeats a set of instructions until a specified condition, called a stopping condition is reached.
The For Loop
A for loop contains three expressions separated by ; inside the parentheses:
- an initialization starts the loop and can also be used to declare the iterator variable.
- a stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.
- an iteration statement is used to update the iterator variable on each loop.
Looping through Arrays
To loop through each element in an array, a for loop should use the array’s .length property in its condition.
Nested Loops
When we have a loop running inside another loop, we call that a nested loop. One use for a nested for loop is to compare the elements in two arrays. For each round of the outer for loop, the inner for loop will run completely.
The While Loop
When to use a while loop! The syntax of a while loop is ideal when we don’t know in advance how many times the loop should run.
Do...While Statements
A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met.
Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.
The break Keyword
The break keyword allows programs to “break” out of the loop from within the loop’s block.
With breaks, we can add test conditions besides the stopping condition, and exit the loop when they’re met.