For Loop
Learn how to use the for loop in JavaScript to repeat blocks of code efficiently with a counter, condition, and update statement.
What is a For Loop?Link to this section
A for loop is a control flow statement that repeats a block of code a specific number of times. It is ideal for situations where you know beforehand how many iterations are required.
This loop starts at 0, runs as long as i is less than 3, and increases i by 1 after each run.
- `for` is the **keyword** that starts the loop.
- `let i = 0;` is the **initialization** part that sets the starting counter.
- `i < 3;` is the **condition** that must be true for the loop to keep running.
- `i++` is the **increment/update** part that changes the counter after each loop.
It is used when you need to repeat an action a set number of times without writing duplicate code.
Why Do We Need a For Loop?Link to this section
Writing the same line of code over and over causes errors and wastes time, which loops solve easily.
- Print numbers from 1 to 100 on a report card.
- Calculate the total price of 10 items in a shopping cart.
- Loop through a list of student exam marks to find the average.
- Display a series of weekly salary payouts.
- Generate a table of monthly utility bills.
- Access every item in an inventory list by its index.
- Repeat an animation frame a specific number of times.
Adding 10 to the total three times gives 30.
Instead of writing total += 10 three times, the loop automates the addition process cleanly.
About the For LoopLink to this section
The for loop manages its own counter variable in the parentheses header. It executes the initialization once, checks the condition before each loop, runs the body code, and then runs the update expression. You can group loops, skip steps, or exit early using flow control keywords.
| Part | Purpose | Example |
|---|---|---|
| Initialization | Sets starting value | let i = 0 |
| Condition | Stops loop when false | i < 10 |
| Update | Changes counter each turn | i++ |
A for loop can also count backwards by decrementing the counter.
Variations and Patterns of For LoopsLink to this section
1. Standard For LoopLink to this section
The traditional loop structure with initialization, condition, and increment expressions separated by semicolons.
Prints Item 0, Item 1, and Item 2.
tip
2. Looping Through ArraysLink to this section
Using a for loop combined with an array's length property to examine every element in a list.
Iterates through each element in the prices array.
warning
3. Skipping Steps with Step ValuesLink to this section
The update expression does not have to increase by 1. You can add any value to jump through numbers.
Prints only even numbers by incrementing i by 2.
note
4. Nested For LoopsLink to this section
Putting a for loop inside another for loop to handle multi-dimensional data, like grid coordinates or multiplication tables.
The inner loop runs completely for every single step of the outer loop.
warning
5. Infinite For LoopsLink to this section
A loop whose condition never becomes false, causing it to run forever unless stopped manually or via code.
This loop would be infinite without the break statement.
warning
6. Omitting Loop PartsLink to this section
You can leave out parts of the for loop header if initialization or updates happen elsewhere.
Initialization is outside, and update is inside the loop body.
tip
Break and Continue StatementsLink to this section
Control the flow inside a loop using break to exit immediately or continue to skip the current iteration and move to the next one.
The number 3 is skipped because of the continue statement.
note
Variable Scope with Let and VarLink to this section
Using let creates block scope inside the loop, while var leaks the variable outside the loop body.
Using let prevents the counter variable from polluting the outer scope.
tip
Complete Coding ExampleLink to this section
Calculates the total cost of items in a shopping cart using a for loop.
This complete example iterates through an array of prices, adds each item to a running total, and prints the final bill.
Important NotesLink to this section
- A for loop has three parts in its header: initialization, condition, and update.
- Semicolons separate the three parts inside the loop parentheses.
- The loop continues to run as long as the condition evaluates to true.
- Always ensure the condition eventually becomes false to avoid infinite loops.
- Use `let` to declare loop counters so they stay contained within the loop block.
- Array indices start at 0, so loops usually start at `i = 0`.
- Use `i < array.length` rather than `<=` to avoid out-of-bounds errors.
- The `break` statement stops the loop entirely.
- The `continue` statement skips the rest of the current loop iteration.
- For loops can count backwards by decrementing the counter variable.
SummaryLink to this section
The for loop is a fundamental tool in JavaScript for repeating code tasks with precision. By managing initialization, condition, and updates in one line, it keeps code clean and manageable. Mastering for loops prepares you for handling arrays, lists, and complex data structures in future programming tasks.
Check Your UnderstandingLink to this section
Which part of the for loop runs only once at the very beginning?
Practice ChallengesLink to this section
1. Print Numbers 1 to 5
Write a for loop that prints numbers from 1 to 5 to the console.
Expected output
1
2
3
4
5Hint: Start your counter at 1 and run while i <= 5.
2. Print Even Numbers
Write a for loop that prints all even numbers from 0 to 6 inclusive.
Expected output
0
2
4
6Hint: Increment your counter by 2 each time.
3. Sum of First 4 Numbers
Use a for loop to calculate the sum of numbers from 1 to 4 and print the final sum.
Expected output
10Hint: Add each number to a running total variable inside the loop.
4. Array Item Printer
Given an array ['apple', 'banana', 'cherry'], use a for loop to print each fruit.
Expected output
apple
banana
cherryHint: Use array.length in your loop condition.
5. Countdown Timer
Write a for loop that counts backwards from 3 down to 1.
Expected output
3
2
1Hint: Initialize i = 3, check i > 0, and decrement with i--.
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion