Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript for Loop

Master the classic for loop in JavaScript. Learn iteration control, array traversal, and efficient counting patterns.

Why this matters

for loops are fundamental to programming. They allow you to repeat operations efficiently, process arrays, and handle iterative tasks that would be impractical to write out manually.

What is a for Loop?

The for loop is the most common type of loop in JavaScript. It allows you to execute a block of code repeatedly for a specified number of times.

It's particularly useful when you know exactly how many times you want to iterate, or when you need to iterate over arrays with index access.

Basic for Loop

for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}

// Output:
// Iteration: 0
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4

This loop runs 5 times, with i starting at 0 and incrementing by 1 each time until i < 5 is false.

for Loop Syntax

The for loop has three parts in its parentheses: initialization, condition, and increment/decrement.

Each part is separated by semicolons and controls different aspects of the loop execution.

for Loop Structure

for (initialization; condition; increment/decrement) {
  // code to execute each iteration
}

The three parts work together: initialize counter, check condition, update counter.

Parts Breakdown

for (let i = 0;     // 1. Initialization - runs once at start
     i < 10;        // 2. Condition - checked before each iteration
     i++) {         // 3. Increment - runs after each iteration

  console.log(i);  // Loop body - executes while condition is true
}

Understanding each part helps you control loop behavior precisely.

Common for Loop Patterns

Different initialization, condition, and increment patterns serve different purposes.

Counting Up

// Count from 1 to 10
for (let i = 1; i <= 10; i++) {
  console.log(i);
}

Start at 1, go up to and including 10, increment by 1.

Counting Down

// Count from 10 to 1
for (let i = 10; i >= 1; i--) {
  console.log(i);
}

Start at 10, go down to 1, decrement by 1.

Even Numbers

// Print even numbers from 0 to 20
for (let i = 0; i <= 20; i += 2) {
  console.log(i);
}

Increment by 2 to get only even numbers.

Custom Increment

// Count by 5s
for (let i = 0; i <= 50; i += 5) {
  console.log(i);
}

Any increment value works - here we count by 5s.

Array Iteration with for Loops

for loops are excellent for iterating over arrays when you need the index or want to modify the array.

Iterate with Index

let fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}

// Output:
// Fruit 1: apple
// Fruit 2: banana
// Fruit 3: orange

Access both index (i) and value (fruits[i]) in each iteration.

Modify Array Elements

let numbers = [1, 2, 3, 4, 5];

// Double each number
for (let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i] * 2;
}

console.log(numbers); // [2, 4, 6, 8, 10]

Modify array elements directly using their indices.

Reverse Array

let arr = [1, 2, 3, 4, 5];

// Swap elements from start and end
for (let i = 0; i < arr.length / 2; i++) {
  let temp = arr[i];
  arr[i] = arr[arr.length - 1 - i];
  arr[arr.length - 1 - i] = temp;
}

console.log(arr); // [5, 4, 3, 2, 1]

Reverse array by swapping elements from both ends moving toward the center.

Nested for Loops

for loops can be nested inside each other to handle multi-dimensional data or complex iterations.

Multiplication Table

// Print multiplication table 1-5
for (let i = 1; i <= 5; i++) {
  for (let j = 1; j <= 5; j++) {
    console.log(`${i} × ${j} = ${i * j}`);
  }
  console.log("---"); // separator
}

Outer loop controls rows, inner loop controls columns.

2D Array Iteration

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
  }
}

Iterate through each element of a 2D array using nested loops.

for vs Other Loops

Different loop types serve different purposes. Choose based on your specific needs.

  • Use for when you know the number of iterations or need index access
  • Use for...of for simple array iteration without indices
  • Use for...in for object property iteration
  • Use while when the number of iterations is unknown
  • Use do...while when you need at least one execution

for vs for...of

let fruits = ["apple", "banana", "orange"];

// Use for when you need index
for (let i = 0; i < fruits.length; i++) {
  console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}

// Use for...of for simple iteration
for (let fruit of fruits) {
  console.log(fruit);
}

Choose the right loop type for your specific use case.

Best Practices

Following best practices makes your for loops more readable and less error-prone.

  • Use meaningful variable names (i, j, k are conventional for indices)
  • Cache array length in the condition to avoid recalculating
  • Use const for loop variables when not modifying them
  • Keep loop bodies small and focused
  • Consider for...of or array methods for simple iterations
  • Add comments for complex loop logic

Cache Array Length

let arr = [1, 2, 3, 4, 5];

// Good: Cache length
for (let i = 0, len = arr.length; i < len; i++) {
  console.log(arr[i]);
}

// Avoid: Recalculate length each iteration
for (let i = 0; i < arr.length; i++) { // arr.length recalculated each time
  console.log(arr[i]);
}

Caching array length improves performance, especially for large arrays.

Common Mistakes

  • Off-by-one errors: Be careful with loop bounds. Use < for arrays, <= for counting to a number.
  • Infinite loops: Ensure the loop condition will eventually become false.
  • Modifying loop counter inside loop: Avoid changing the loop variable inside the loop body unless intentional.

Frequently Asked Questions

When should I use a for loop instead of for...of?

Use for loop when you need the index, want to modify the array, or need more control over iteration.

Can I declare the loop variable with const?

No, because the variable needs to be reassigned each iteration. Use let instead.

What happens if I don't include all three parts of the for loop?

You can omit parts, but semicolons are still required. For example: for(;;) creates an infinite loop.