Using for Loop


The for loop is one of the most commonly used loops in JavaScript. It is perfect when you know in advance how many times a block of code should run.

A for loop has three parts:

  1.  Initialization – where the loop starts
  2. Condition – when the loop should stop  
  3. Update – how the loop changes each time  

Understanding these three parts helps you control repetition easily.

When to Use the for Loop

  • When repeating code a fixed number of times 
  • When counting numbers
  • When looping through lists or arrays  
  • When generating tables or patterns  
  • When processing data step by step  

The for loop gives you full control over how many times code runs.

In this example, the loop starts with i = 1 and runs as long as i is less than or equal to 5.

After each run, the value of i increases by 1. This shows how the loop controls repetition.

Here, the loop counts backwards from 5 to 1. The update part uses i-- to decrease the value of i.

This is useful in timers, countdowns, and reverse processing.

This example shows how a for loop can perform calculations while repeating code.

By mastering the for loop, students can handle repetition, perform data processing, and build strong logic for real-world applications.