Hello! In our last lesson, we established why loops are a fundamental part of programming: they save us from writing repetitive code, making our programs more efficient and maintainable. We used the analogy of hammering a nail—you repeat the action until a condition is met.
Today, we transition from the "why" to the "how." You'll learn to write the most common type of loop in JavaScript, the for loop. This loop is your go-to tool when you know exactly how many times you want to repeat a task. Mastering this is a crucial step toward building dynamic applications, where you might need to display a specific number of items, like the top 10 products on an e-commerce site.
The Anatomy of a for Loop
Let's go back to our simple problem: printing a message to the console five times. Instead of writing five separate console.log() statements, we can use a for loop.
The syntax looks a bit complex at first, but it's very structured. It consists of three parts inside the parentheses, separated by semicolons:
for (initialization; condition; finalExpression) {// code to be executed in each repetition}
To see this broken down clearly, let's watch a short video.
The video "JavaScript Loops" by Programming with Mosh provides an excellent, beginner-friendly breakdown of the for loop's syntax. He explains each of the three parts in a very clear way.
Watch the segment from the beginning until 02:47. Focus on understanding the role of the three statements inside the parentheses: the initial expression, the condition, and the increment expression.
As Mosh explained, these three parts control the loop's entire lifecycle:
- Initialization (
let i = 0;): This runs only once at the very beginning. We declare a counter variable, conventionally namedi(for "index"), and initialize it. Starting at0is a very common practice in programming. - Condition (
i < 5;): This is checked before every loop iteration. If the condition istrue, the code inside the loop's curly braces{}runs. If it'sfalse, the loop stops completely. - Final Expression (
i++): This runs after every iteration, just before the condition is checked again. Its job is to update the counter variable, moving it closer to making the conditionfalse.i++is shorthand fori = i + 1.
So, to print "Hello World" five times, we would write:
for (let i = 0; i < 5; i++) {
console.log("Hello World");
}
This code does the exact same thing as writing console.log() five times, but it's much more flexible. If we wanted to run it 100 times, we would only need to change 5 to 100.
Visualizing the Execution Flow
Since you prefer visual explanations, let's map this process onto a flowchart. This visual model is key to understanding how the JavaScript engine executes a for loop.

Let's trace our example, for (let i = 0; i < 5; i++), using this flow:
- Initialize:
let i = 0. The variableiis created and set to 0. This happens only once. - Check Condition: Is
i < 5? Yes, because0 < 5. The condition istrue. - Execute Statement: The code
console.log("Hello World")runs. - Increment:
i++runs.iis now1. - Check Condition: Is
i < 5? Yes, because1 < 5. The condition istrue. - Execute Statement:
console.log("Hello World")runs again. - Increment:
i++runs.iis now2. - ...This cycle continues until
iis4. The condition4 < 5is true, the message is printed, andibecomes5. - Check Condition: Is
i < 5? No, because5is not less than5. The condition isfalse. - End: The loop terminates, and the program continues with any code written after the loop.
To see an even more detailed, step-by-step breakdown, the following article provides a fantastic table format that tracks the loop's state at each iteration.
JavaScript for loop (with Examples)
The article "JavaScript for loop" from Programiz offers a very clear table that walks through each iteration of a loop. This will solidify your mental model of the execution flow.
Read the section "Example 1: Print Numbers From 1 to 5" and pay close attention to the table that shows how the variable i, the condition, and the action change with each iteration. This is a text-based version of the flowchart we just saw.
Test your understanding!
Consider the following loop:
for (let i = 3; i < 7; i++) {
console.log(i);
}
What will be the exact output in the console? Try to trace it step-by-step in your head before checking the answer.
Show answer
The output will be:
3
4
5
6
Explanation:
istarts at3.3 < 7is true, so3is printed.ibecomes4.4 < 7is true, so4is printed.ibecomes5.5 < 7is true, so5is printed.ibecomes6.6 < 7is true, so6is printed.ibecomes7.7 < 7is false, so the loop stops.
Common Variations and Pitfalls
Counting Backwards and Combining with Conditionals
You are not limited to counting up. By changing the three parts of the loop, you can iterate in different ways. For example, you can count backwards:
// A countdown from 5 to 1
for (let i = 5; i > 0; i--) {
console.log(i);
}
console.log("Blastoff!");
Here, we initialize i to 5, continue as long as i is greater than 0, and decrement i (i--) after each step.
You can also place other control flow structures, like the if statements you've already learned, inside a loop.
Let's return to the video from Programming with Mosh. He demonstrates how to write a loop that counts backward and, more interestingly, how to use an if statement inside a loop to solve a problem.
Watch the segment from 04:01 to 05:54. Notice how he combines a loop with a conditional to display only the odd numbers within a range.
A Critical Pitfall: The "Off-by-One" Error
One of the most common bugs all programmers face when writing loops is the "off-by-one" error. This happens when your loop runs one time too many or one time too few. It's usually caused by an incorrect condition.
Consider a list (an array) of three items: ['a', 'b', 'c'].
In JavaScript, items in a list are indexed starting from 0. So, the index of 'a' is 0, 'b' is 1, and 'c' is 2. The total number of items (the length) is 3.
Notice that the last index is always length - 1.
A correct loop to go through these items would be:for (let i = 0; i < 3; i++)
This runs for i = 0, i = 1, and i = 2. Perfect.
A common mistake is to write:for (let i = 0; i <= 3; i++)
This loop will run for i = 0, 1, 2, and 3. When i is 3, the program will try to access the item at index 3, which doesn't exist, causing an error.
Rule of thumb: When iterating through an indexed list from the beginning, your condition should almost always be i < list.length.
Test your understanding!
What is wrong with the following code? How many times will "Sending notification..." be printed, and why is this likely a bug?
const userCount = 10;
// Loop to send a notification to each of the 10 users
for (let i = 1; i < userCount; i++) {
console.log("Sending notification...");
}
Show answer
The loop will only run 9 times, not 10.
Explanation:
The loop starts with i = 1 and the condition is i < 10. It will run for i = 1, 2, 3, 4, 5, 6, 7, 8, and 9. When i becomes 10, the condition 10 < 10 is false, and the loop stops. This is an off-by-one error because it misses the 10th user.
To fix this, you could either change the condition to i <= userCount or, more idiomatically, start the loop at 0 and use the condition i < userCount:for (let i = 0; i < userCount; i++)
Conclusion
In this lesson, you've learned the syntax and logic of the fundamental for loop. We've dissected its three core components and visualized its execution flow to build a solid mental model of how it works "under the hood."
Key Takeaways:
- A
forloop is used to execute a block of code a specific number of times. - It is controlled by three parts: initialization (runs once), a condition (checked before each iteration), and a final expression (runs after each iteration).
- The loop continues as long as the condition evaluates to
true. - You can control the iteration by changing the three parts, allowing you to count up, down, or in other increments.
- Be mindful of "off-by-one" errors by carefully setting your loop's condition, especially when working with 0-indexed data like arrays (where the condition is typically
i < length).
Next Up:
The for loop is perfect when you know the number of iterations in advance. But what if you don't? What if you need to repeat an action until a certain event happens, like a user clicking a button or a file finishing its download? For those scenarios, we use other types of loops. In the next lesson, we'll explore while and do...while loops, which are condition-based rather than counter-based.