For Loop
Another type of loop in JavaScript is the for
loop, which allows us to repeatedly execute a block of code similarly to the while
loop. The for
loop is often used when we know how many times we want to perform an operation or when we want to go through all the elements in a sequence. On the other hand, the while
loop is used when we do not know how many times we need to repeat the loop.
The for
loop consists of three parts separated by a semicolon (;
):
- An iteration variable, to which we assign a value in the first part.
- A condition, which as long as it is true, the loop will repeat.
- A change in the value of the iteration variable.
The structure of the for
loop looks as follows:
for (let counter = 0; counter < 3; counter++) {
console.log(counter);
}
This will print:
0
1
2
The notation counter++
is a shorthand for counter = counter + 1
. This only increases the value of counter
by 1.
Step by step, it will perform:
- Create an iteration variable
counter
with a value of0
. - The condition is
counter < 3
, which means the loop will repeat as long ascounter
is less than 3. counter++
increases the value ofcounter
by 1 at the end of each iteration. In the first iteration, it will have a value of 0. In the second iteration, it will have a value of 1, and so on.- The code inside the curly braces,
console.log(counter);
, will run in each iteration until the condition isfalse
. The condition will befalse
whencounter
is greater than or equal to3
.
Instructions
Using a for
loop, print the numbers from 15 to 20 inclusive.
Start programming for free
3/9