Introduction to loops
We often need to repeat actions. Like, outputting goods from a list one after another, or just running the same code for each number from 1 to 10.
Loops offer a quick and easy way to do something repeatedly by executing a block of code a number of times.
You can think of a loop as a computerized version of the game, where you tell someone to take X steps in one direction, then Y steps in another. For example, the idea "Go five steps to the east" could be expressed this way as a loop:
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log('Walking east one step');
}
There are many different kinds of loop mechanisms that offer different ways to determine the start and end points of the loop, but they all essentially do the same thing: they repeat an action some number of times. However, there are some occasions where one type of these loops can be more useful than the others. And for this pre-course, we’ll just focus on the following 2:
- The
for
loop. - The
while
loop.
The For Loop
A for
loop repeats until a specified condition evaluates to false. It creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
- Expression 1 is executed (one time) before the execution of the code block.
- Expression 2 defines the condition for executing the code block.
- Expression 3 is executed (every time) after the code block has been executed.
Example:
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
The JavaScript
for
loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.
The While Loop
The while
loop loops through a block of code as long as a specified condition is true.
while (condition) {
// code block to be executed
}
If the condition becomes false, the code within the loop stops executing and control passes to the code following the loop.
Example:
while (i < 10) {
text += "The number is " + i;
i++;
}
If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
You can learn more about loops through this video: