For Loop in JavaScript

The for loop is one of the most commonly used loops in JavaScript. It helps us repeat a block of code a specific number of times. Whether you want to count numbers, go through items in a list, or repeat a task, a for loop is a great way to do it in a clean and simple way.

Loop Structure

A for loop has three parts inside its parentheses: the starting point, the condition to keep looping, and how to move to the next step. These three parts are separated by semicolons.

javascript
1
2
3
          for (let i = 0; i < 5; i++) {
  console.log(i);
}
        
  • let i = 0 is where the loop starts (i is the counter).
  • i < 5 is the condition. The loop keeps going as long as this is true.
  • i++ means we increase i by 1 after each loop.

This loop will print: 0, 1, 2, 3, 4.

Counting Up and Down

You can count forward or backward with a for loop.

Counting Up:

javascript
1
2
3
          for (let i = 1; i <= 5; i++) {
  console.log(i);
}
        

This prints numbers from 1 to 5.

Counting Down:

javascript
1
2
3
          for (let i = 5; i >= 1; i--) {
  console.log(i);
}
        

This prints numbers from 5 to 1.

Using `i` with Arrays

When working with arrays, we often use a for loop to go through each item by its index.

javascript
1
2
3
4
5
          let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
        

In this loop:

  • i starts at 0.
  • fruits.length tells the loop when to stop.
  • fruits[i] gives us each item in the array by its position.

Skipping and Breaking

You can use continue to skip a step, or break to stop the loop early.

javascript
1
2
3
4
          for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);
}
        

This skips 2 and prints 0, 1, 3, 4.

javascript
1
2
3
4
          for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);
}
        

This stops the loop at 3 and prints 0, 1, 2.

Nested For Loops

You can put a for loop inside another for loop. This is useful for working with multi-level data like tables.

javascript
1
2
3
4
5
          for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(i, j);
  }
}