Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript for Loop

The for loop is the most common loop when you know exactly how many times to iterate.

It keeps initialization, condition, and step in one concise line.

Why We Need It

Index-based loops are helpful for arrays, pagination, and fixed counts.

A well-structured for loop is easy to read and efficient.

Syntax

for (init; condition; step) { ... }

Basic Example

1. Basic for loop

for (let i = 0; i < 3; i++) {
  console.log(i);
}

A standard for loop counts from 0 to 2.

Real World Example

2. Loop over array

const items = ["a", "b", "c"];

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

Use indices when you need the position.

Multiple Use Cases

Known Iterations

Use a for loop when you know how many times you need to run a block.

It combines initialization, condition, and increment in one place.

Indices and Counters

for loops are great for index-based iteration over arrays.

Be mindful of the start and end conditions to avoid off-by-one errors.

Nested Loops

Nested loops are useful for grids and combinations, but can be expensive.

Keep the inner work light and avoid unnecessary nesting.

More Examples

3. Step by 2

for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}

Adjust the increment to skip values.

4. Reverse loop

for (let i = 5; i >= 0; i--) {
  console.log(i);
}

You can count down as well.

Comparison

Without

let i = 0;
console.log(i);
i++;
console.log(i);
i++;

With

for (let i = 0; i < 2; i++) {
  console.log(i);
}

Common Mistakes and Fixes

Off-by-one errors

Double-check loop boundaries (use < vs <= intentionally).

Using length in condition repeatedly

Cache length if needed for performance in hot loops.

Forgetting i++

Ensure the counter changes so the loop can finish.

Mutating array length while looping

Avoid changing the array you are iterating unless necessary.

Interview Questions

What are the three parts of a for loop?

Initialization, condition, and increment (step).

How do you avoid off-by-one errors?

Be explicit about whether the end index is inclusive or exclusive.

When is for...of better?

When you only need the values, not the index.

Practice Problem

Practice: Print the first 10 even numbers using a for loop.

// TODO: print 0 to 18 step 2

One Possible Solution

for (let i = 0; i < 20; i += 2) {
  console.log(i);
}

Frequently Asked Questions

When should I use for vs for...of?

Use for when you need the index, for...of when you only need values.

Can the increment be negative?

Yes, you can count down with i--.

Is for faster than array methods?

Often similar; choose readability first unless performance is critical.

Try It Yourself

Try changing the loop bounds and step to see how iteration changes.