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 (;):

  1. An iteration variable, to which we assign a value in the first part.
  2. A condition, which as long as it is true, the loop will repeat.
  3. 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:

  1. Create an iteration variable counter with a value of 0.
  2. The condition is counter < 3, which means the loop will repeat as long as counter is less than 3.
  3. counter++ increases the value of counter 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.
  4. The code inside the curly braces, console.log(counter);, will run in each iteration until the condition is false. The condition will be false when counter is greater than or equal to 3.

Instructions

Using a for loop, print the numbers from 15 to 20 inclusive.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/9

For Loop | Start Coder