Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

7 Loops

2 For Loop

A for loop is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of times. It is particularly useful when you know in advance how many times you want to execute a certain block of code.

Here's the basic structure of a for loop:

for (initialization; condition; incrementOrDecrement) {
    // Code to be executed
}

Initialization

This part initializes a loop control variable and is executed before the loop begins. It usually initializes a counter variable to keep track of the number of iterations.

Condition

This part defines the condition for executing the loop. The loop continues to execute as long as this condition evaluates to true.

Increment or Decrement

This part specifies how the loop control variable is modified after each iteration. It's typically used to increment or decrement the loop counter.

Example

Let's look at an example:

for (let i = 0; i < 5; i++) {
    console.log("Iteration: " + i);
}

In this example:

  • Initialization: let i = 0 initializes the loop counter i to 0.
  • Condition: i < 5 specifies that the loop should continue as long as i is less than 5.
  • Increment: i++ increments the value of i by 1 after each iteration.

The loop will execute five times, with i taking on the values 0, 1, 2, 3, and 4 in each iteration. After the fifth iteration, the condition i < 5 will evaluate to false, and the loop will terminate.