Introduction to For Loops in JavaScript
When you want to repeat a block of code multiple times, instead of writing it again and again, you use loops. The most common loop is the for loop.
What is a For Loop?
A for loop runs a block of code a specific number of times — great for going through arrays, counting, or repeating tasks.
Basic Syntax of a For Loop
-
Initialization: Start point (usually a counter variable)
-
Condition: Runs the loop while this is true
-
Update: What happens after each loop iteration (e.g., increment counter)
Example: Counting from 1 to 5
Output:
Breaking Down the Example
-
let i = 1;— Start counting at 1 -
i <= 5;— Continue loop as long asiis less than or equal to 5 -
i++— Increaseiby 1 each time (same asi = i + 1)
Using For Loops with Arrays
You can loop through an array’s elements like this:
Output:
Why Use For Loops?
-
Automate repetitive tasks
-
Process every item in a list or array
-
Write cleaner, shorter code
Summary
| Part | Meaning |
|---|---|
| Initialization | Where to start (e.g., let i = 0) |
| Condition | When to keep looping (i < 10) |
| Update | How to change each loop (i++) |
