JavaScript for Loop
Table of Contents + −
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.
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 (let i = 0; i < 5; i++) { console.log(i);}Let’s read this loop piece by piece:
let i = 0creates the counter and sets its starting value to0.i < 5is the condition that is checked before every pass; the loop keeps going while it istrue.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 (let i = 1; i <= 5; i++) { console.log(i);}// 1// 2// 3// 4// 5Here is what happens on each step:
let i = 1starts the counter at1instead of0, so the first number printed is1.i <= 5keeps the loop running untilipasses5, which is why5is included.console.log(i)prints the counter, theni++raises it for the next pass.- When
ibecomes6, the conditioni <= 5isfalse, 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.
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}// apple// banana// cherryLet’s trace how this reaches each fruit:
fruitsholds three values at positions0,1, and2.i < fruits.lengthruns the loop whileiis0,1, and2, sincefruits.lengthis3.fruits[i]reads the item at the current index, so we printapple, thenbanana, thencherry.
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.
const prices = [10, 25, 5, 60];let total = 0;
for (let i = 0; i < prices.length; i++) { total = total + prices[i];}
console.log(total); // 100Let’s follow the running total:
let total = 0sets the starting sum before the loop begins.total = total + prices[i]adds the current price tototalon each pass.- The loop visits
10,25,5, and60in turn, building the total up to100. 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.
const colors = ["red", "green", "blue"];
// ❌ Wrong: i reaches 3, but colors[3] does not existfor (let i = 0; i <= colors.length; i++) { console.log(colors[i]); // red, green, blue, undefined}
// ✅ Correct: i stops at 2, the last valid indexfor (let i = 0; i < colors.length; i++) { console.log(colors[i]); // red, green, blue}Let’s compare the two conditions:
colors.lengthis3, but the valid indexes are only0,1, and2.- The wrong loop uses
i <= colors.length, soireaches3andcolors[3]isundefined. - The correct loop uses
i < colors.length, soistops at2and 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!
- Write a
forloop that prints the numbers from 1 to 10. - Create an array of names and loop over it, printing each name with its index.
- Build a loop that adds up all the numbers in an array and prints the total.
- 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
forloop 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
0tolength - 1 - ✅ Use
i < arr.lengthto 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.