JavaScriptLoops, Arrays & Strings

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.

PartPurposeExample
InitializationSets starting valuelet i = 0
ConditionStops loop when falsei < 10
UpdateChanges counter each turni++

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

Always declare your counter variable using `let` inside the loop header to keep its scope limited to the loop block.

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

Using `<=` instead of `<` with array lengths causes an "undefined" error because it tries to access an index that does not exist.

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

You can count by tens, hundreds, or any custom step size by changing the increment value.

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

Avoid deep nesting (3+ loops) when possible, as it slows down program performance significantly.

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

Accidental infinite loops freeze browsers and Node.js applications. Always make sure your counter moves toward making the condition false.

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

Semicolons inside the for parentheses are still required even if expressions are omitted.

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

`break` stops the entire loop, whereas `continue` only skips the current turn.

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

Always use `let` for loop counters in modern JavaScript.

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

Javascript For Loop quiz
Question 1 of 7

Which part of the for loop runs only once at the very beginning?

Practice ChallengesLink to this section

1. Print Numbers 1 to 5

easy

Write a for loop that prints numbers from 1 to 5 to the console.

Expected output

1
2
3
4
5

Hint: Start your counter at 1 and run while i <= 5.

2. Print Even Numbers

easy

Write a for loop that prints all even numbers from 0 to 6 inclusive.

Expected output

0
2
4
6

Hint: Increment your counter by 2 each time.

3. Sum of First 4 Numbers

medium

Use a for loop to calculate the sum of numbers from 1 to 4 and print the final sum.

Expected output

10

Hint: Add each number to a running total variable inside the loop.

4. Array Item Printer

medium

Given an array ['apple', 'banana', 'cherry'], use a for loop to print each fruit.

Expected output

apple
banana
cherry

Hint: Use array.length in your loop condition.

5. Countdown Timer

hard

Write a for loop that counts backwards from 3 down to 1.

Expected output

3
2
1

Hint: Initialize i = 3, check i > 0, and decrement with i--.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion