JavaScript for Loop

In the previous lesson, we learned how to choose between two values with the ternary operator. Now let’s learn how to repeat code with the for loop.

🔁 Why Loops Exist

Imagine we want to print the numbers 1 to 5. Without a loop, we would write the same line five times.

for-loop.js
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);

Each line prints one number, so we repeat console.log five times to cover 1 through 5. This works, but it is repetitive, and printing 1 to 1000 would be unbearable. A loop lets us run the same code many times without copying it. The for loop is the most common loop in JavaScript, and it is perfect when we know how many times we want to repeat.

🧱 The Three Parts of a for Loop

A for loop packs everything it needs into one line, separated by semicolons.

for-loop.js
for (let i = 0; i < 5; i++) {
console.log(i);
}

Let’s read this loop piece by piece:

  • let i = 0 creates the counter and sets its starting value to 0.
  • i < 5 is the condition that is checked before every pass; the loop keeps going while it is true.
  • i++ runs after each pass and adds one to the counter.
  • console.log(i) is the body, and it prints the current counter value each time through.

The part inside the parentheses has three sections. Let’s break them down.

Part Example What it does
Initialization let i = 0 Runs once at the start to set up the counter
Condition i < 5 Checked before each loop; the loop runs while it is true
Update i++ Runs after each loop to change the counter

The counter i starts at 0, the loop keeps running while i is less than 5, and i grows by one each time. The code inside the curly braces runs once for every pass.

Why i?

The variable i stands for “index” and is the traditional name for a loop counter. We can name it anything, but i is what most programmers expect.

🔢 Printing 1 to 5

Let’s print the numbers 1 through 5. We start the counter at 1 and keep going while it is less than or equal to 5.

for-loop.js
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// 1
// 2
// 3
// 4
// 5

Here is what happens on each step:

  • let i = 1 starts the counter at 1 instead of 0, so the first number printed is 1.
  • i <= 5 keeps the loop running until i passes 5, which is why 5 is included.
  • console.log(i) prints the counter, then i++ raises it for the next pass.
  • When i becomes 6, the condition i <= 5 is false, so the loop stops.

📋 Looping Over an Array

Arrays store a list of values, and a for loop is a great way to visit each one. We use the counter as the index, starting at 0 because array positions begin at 0.

for-loop.js
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// apple
// banana
// cherry

Let’s trace how this reaches each fruit:

  • fruits holds three values at positions 0, 1, and 2.
  • i < fruits.length runs the loop while i is 0, 1, and 2, since fruits.length is 3.
  • fruits[i] reads the item at the current index, so we print apple, then banana, then cherry.

Use length, not a fixed number

Writing i < fruits.length lets the loop adapt automatically if the array grows or shrinks. Avoid hard-coding the size.

➕ A Practical Example: Summing Numbers

A common task is adding up a list of numbers. We keep a running total in a variable and add each value to it inside the loop.

for-loop.js
const prices = [10, 25, 5, 60];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total = total + prices[i];
}
console.log(total); // 100

Let’s follow the running total:

  • let total = 0 sets the starting sum before the loop begins.
  • total = total + prices[i] adds the current price to total on each pass.
  • The loop visits 10, 25, 5, and 60 in turn, building the total up to 100.
  • console.log(total) prints the final sum after the loop finishes.

⚠️ Common Mistakes to Avoid

Mistake Problem Solution
Using <= with length i <= arr.length reads past the last index and gives undefined Use i < arr.length so the last index is length - 1
Forgetting the update Without i++ the condition never changes, so the loop runs forever Always update the counter toward the condition
Changing i inside the loop Editing the counter in the body makes the loop hard to follow Let the update section handle the counter

The first mistake is the classic “off-by-one” error. Let’s see the difference clearly.

for-loop.js
const colors = ["red", "green", "blue"];
// ❌ Wrong: i reaches 3, but colors[3] does not exist
for (let i = 0; i <= colors.length; i++) {
console.log(colors[i]); // red, green, blue, undefined
}
// ✅ Correct: i stops at 2, the last valid index
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]); // red, green, blue
}

Let’s compare the two conditions:

  • colors.length is 3, but the valid indexes are only 0, 1, and 2.
  • The wrong loop uses i <= colors.length, so i reaches 3 and colors[3] is undefined.
  • The correct loop uses i < colors.length, so i stops at 2 and we print only the real values.

Watch for infinite loops

If the condition never becomes false, the loop never stops and can freeze the page. Make sure the update moves the counter closer to ending the loop.

🔧 Try It Yourself!

  1. Write a for loop that prints the numbers from 1 to 10.
  2. Create an array of names and loop over it, printing each name with its index.
  3. Build a loop that adds up all the numbers in an array and prints the total.
  4. Change a working loop’s condition from < to <= and watch the off-by-one bug appear.

🧩 What You’ve Learned

  • ✅ Loops repeat code without copying it line by line
  • ✅ A for loop has three parts: initialization, condition, and update
  • ✅ The condition is checked before each pass, and the update runs after
  • ✅ We loop over arrays using an index from 0 to length - 1
  • ✅ Use i < arr.length to avoid off-by-one errors, and always update the counter to avoid infinite loops

🚀 What’s Next?

Now that we can repeat code a set number of times, we will learn a loop that runs as long as a condition stays true. Let’s continue to the while Loop.

Share & Connect