Academic Block

JavaScript for Loop Get Certified

Loops let you run the same block of code multiple times without repeating it manually. The for loop is one of the most common ways to repeat code a specific number of times in JavaScript.

In this lesson, you will learn the syntax of the for loop, how to control it with break and continue, and how to use it with arrays and nested loops.

Basic for Loop Syntax

A for loop consists of three parts separated by semicolons: an initializer, a condition, and an update expression.

What this code does: A classic for loop counts from 1 to 5. i starts at 1, the loop continues while i <= 5, and i++ increases it by 1 each time. The numbers 1 through 5 are printed.

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

This loop prints the numbers 1 through 5. Let’s break down each part of the loop below.

The Three Parts of a for Loop

Part Example Description
Initializer let i = 1 Runs once, before the loop starts
Condition i <= 5 Checked before each iteration; loop stops when false
Update expression i++ Runs after each iteration

What this code does: The counter starts at 0 (common when working with arrays). The loop runs three times (0, 1, 2) and prints the iteration number each time.

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

Counting Down

A for loop can also count downward by starting at a higher number and decrementing.

What this code does: Loops can count downward. Starting at 5 and decreasing with i-- until 1, then “Liftoff!” is printed after the loop finishes.

for (let i = 5; i >= 1; i--) {
    console.log(i);
}
console.log("Liftoff!");

Looping Through an Array

A common use of the for loop is to iterate over the elements of an array using the array’s index.

What this code does: A common pattern: loop from 0 to array.length - 1 and access each element with fruits[i]. Every fruit in the list is printed.

const fruits = ["Apple", "Banana", "Orange"];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

Using fruits.length in the condition ensures the loop automatically adjusts if the array’s size changes.

The break Statement

The break statement immediately stops the loop, even if the condition would still be true.

What this code does: break exits the loop immediately. When i reaches 5, the loop stops, so only 1–4 are printed.

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;
    }
    console.log(i);
}

This loop stops entirely once i reaches 5, so only the numbers 1 through 4 are printed.

The continue Statement

The continue statement skips the rest of the current iteration and moves on to the next one, without stopping the loop entirely.

What this code does: continue skips the rest of the current iteration and jumps to the next one. Even numbers are skipped, so only the odd numbers 1, 3, 5, 7, 9 are printed.

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

This loop skips every even number and only prints odd numbers, since continue jumps straight to the next iteration whenever i is even.

Nested for Loops

A for loop can be placed inside another for loop. This is often used for working with grids, tables, or multi-dimensional data.

What this code does: Nested loops put one loop inside another. The outer loop runs for each row; the inner loop runs for each column. All 9 row/column pairs are printed.

for (let row = 1; row <= 3; row++) {
    for (let col = 1; col <= 3; col++) {
        console.log("Row " + row + ", Col " + col);
    }
}

For each iteration of the outer loop, the entire inner loop runs from start to finish.

Optional Loop Parts

All three parts of a for loop are technically optional, although it’s uncommon to omit them without good reason.

What this code does: Any of the three for parts can be omitted. Here the counter is declared before the loop, so the initializer slot is empty. It still counts 0, 1, 2.

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

Here, the variable i is declared before the loop, so the initializer part is left empty. This is uncommon in practice but valid syntax.

Avoiding Infinite Loops

If the condition never becomes false, the loop will run forever, potentially freezing your program. This is called an infinite loop and is usually a bug.

What this code does: An infinite loop example is shown (commented out) so it cannot freeze the page. The condition i >= 0 never becomes false. Always ensure your condition can eventually stop the loop.

// Be careful! This is an example of an infinite loop.
// for (let i = 0; i >= 0; i++) {
//     console.log(i);
// }
// The condition "i >= 0" is always true, so this loop never stops.
console.log("Always make sure your loop's condition can become false.");

for vs. for…of vs. for…in

JavaScript offers other loop styles built on top of the concept of iteration. The classic for loop gives you full control over the index, while for...of and for...in offer simpler syntax for specific situations.

What this code does: Side-by-side comparison: a classic index-based for versus for...of, which gives each value directly without an index. Both print the same colors.

const colors = ["red", "green", "blue"];
// Classic for loop
for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}
// for...of loop (values)
for (const color of colors) {
    console.log(color);
}

The classic for loop is especially useful when you need the index itself, want to loop in reverse, or want to skip elements using a custom step.

Practical Example

Let’s use a for loop to calculate the sum of numbers in an array.

What this code does: A practical use of a loop: add every number in an array to a running total. After the loop, total holds the sum (150), which is printed.

const numbers = [10, 20, 30, 40, 50];
let total = 0;
for (let i = 0; i < numbers.length; i++) {
    total += numbers[i];
}
console.log("Total:", total);

Common Mistakes With for Loops

  • Writing a condition that never becomes false, causing an infinite loop.
  • Off-by-one errors, such as using <= instead of < (or vice versa) when looping through an array.
  • Using var instead of let for the loop counter, which can cause unexpected behavior with closures inside the loop.
  • Modifying the array being looped over while iterating, which can cause elements to be skipped.
  • Forgetting that continue skips to the next iteration rather than exiting the loop entirely.

Best Practices for for Loops

  • Use let for the loop counter instead of var.
  • Cache array.length in a variable if it’s expensive to compute and won’t change during the loop.
  • Use for...of when you only need the values, not the index.
  • Keep loop bodies short and readable; extract complex logic into a separate function.
  • Double-check your loop’s condition to avoid infinite loops and off-by-one errors.

Quick Summary

  • A for loop has three parts: initializer, condition, and update expression.
  • The loop runs as long as the condition remains true.
  • break exits the loop immediately; continue skips to the next iteration.
  • for loops can be nested to work with grids or multi-dimensional data.
  • An incorrect or missing condition can cause an infinite loop.
  • for...of and for...in offer alternative, simpler syntax for common looping situations.

Try It Yourself

Modify the loop below. Try changing the starting value, the condition, or the update expression, and see how the output changes.

What this code does: Practice example: change the start value, end condition, or step, then click Test My Code to see how the printed sequence changes.

for (let i = 1; i <= 5; i++) {
    console.log("Count:", i);
}
Tip: Before running a loop with a large number of iterations, always double-check that the condition will eventually become false. It’s a small habit that saves a lot of debugging time later.

Understanding the for loop is essential before moving on to while loops, for...of, for...in, functions, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close