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);
}
for ( starts the loop. The first part inside the parentheses, let i = 1, is the initializer. It creates a counter variable named i and sets it to 1. It runs only once, before the loop begins. Because it uses let, the variable exists only inside this loop.i <= 5, is the condition. It is checked before every pass through the loop. While it is true the loop body runs; the first time it is false, the loop ends. The two semicolons ; separate the three parts of the loop header.i++, is the update expression. It runs after each pass of the body and adds 1 to i. Without it, i would always stay 1 and the loop would never end. The opening brace { at the end starts the loop body.console.log(i); is the code that is repeated. On each pass it prints the current value of i. On the first pass i is 1, then 2, 3, 4 and finally 5, so the numbers 1 to 5 are printed, one per line.} ends the loop body. After the pass with i equal to 5, the update makes i equal to 6, the condition 6 <= 5 is false, and the loop stops. The output is 1, 2, 3, 4, 5.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);
}
let i = 0 starts the counter at 0. Counting from 0 is very common in programming, because array positions also start at 0. The condition i < 3 uses < (not <=), so the loop runs while i is 0, 1 or 2 and stops when it reaches 3. i++ adds 1 after each pass. That gives exactly three iterations.console.log can take several values separated by commas, and prints them on one line separated by a space. Each pass prints the text "Iteration number:" followed by the current value of i. The output is Iteration number: 0, Iteration number: 1 and Iteration number: 2.} ends the loop body. When i becomes 3, the condition 3 < 3 is false and the loop stops, so the number 3 is never printed.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!");
let i = 5 starts the counter at the highest number. The condition i >= 1 keeps the loop running while i is 1 or more. The update i-- subtracts 1 after each pass instead of adding. So i takes the values 5, 4, 3, 2, 1, and the loop stops when it becomes 0.console.log(i); prints the current value on each pass, so the output is 5, 4, 3, 2, 1, one number per line.} ends the loop body. Once i reaches 0, the condition 0 >= 1 is false, and JavaScript continues with the code after the loop.Liftoff! as the last line of output.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]);
}
const fruits = ["Apple", "Banana", "Orange"]; creates an array: an ordered list of values inside square brackets. Each item has a numbered position called an index, starting at 0: fruits[0] is "Apple", fruits[1] is "Banana" and fruits[2] is "Orange".let i = 0 starts at the first index. i < fruits.length keeps looping while i is smaller than the number of items (fruits.length is 3), so i goes through 0, 1 and 2, the valid indexes. i++ moves to the next index. Using < and not <= matters: index 3 does not exist.fruits[i] reads the item at position i. On the three passes it gives "Apple", "Banana" and "Orange", and console.log prints each one on its own line.} ends the loop body. Because the condition uses fruits.length, the loop automatically adapts if you add or remove fruits from the array.
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);
}
for (let i = 1; i <= 10; i++) { would normally count from 1 to 10. The break inside the body will stop it earlier.if (i === 5) { tests on every pass whether the counter has reached 5. The === operator checks that the value and the type are equal. For i equal to 1, 2, 3 and 4 this is false and the if block is skipped.break; runs only when i is 5. It ends the whole loop immediately, even though the condition i <= 10 is still true. JavaScript jumps to the first line after the loop’s closing brace.} closes the if block that began on line 2.console.log(i); prints the counter. It runs on passes 1 to 4, because on pass 5 the break happens before this line is reached. The output is 1, 2, 3, 4.} ends the loop body. The numbers 5 to 10 are never printed, because the loop was stopped by break.
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);
}
for (let i = 1; i <= 10; i++) { runs the body once for each number from 1 to 10. Unlike break, continue will not stop this loop; it only skips some passes.if (i % 2 === 0) { uses the remainder operator %. i % 2 gives the remainder when i is divided by 2: it is 0 for even numbers (2, 4, 6, 8, 10) and 1 for odd numbers. So the condition is true only when i is even.continue; stops the current pass immediately and jumps to the update (i++) and then the next pass. The console.log line below is skipped for this value of i, but the loop itself carries on.} closes the if block that began on line 2.console.log(i); is only reached when i is odd, because even numbers were skipped by continue. The output is 1, 3, 5, 7, 9.} ends the loop body. After i becomes 11, the condition i <= 10 is false and the loop ends normally.
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 (let row = 1; row <= 3; row++) { is the outer loop. It controls the rows and runs three times, with row equal to 1, 2 and 3.for (let col = 1; col <= 3; col++) { is the inner loop, written inside the outer loop’s body. A brand-new col starting at 1 is created every time the outer loop starts a new row, and the inner loop runs completely (col 1, 2, 3) before the outer loop moves on.+ operator joins text and numbers into one string, so the output is lines such as Row 1, Col 1, Row 1, Col 2, Row 1, Col 3, then Row 2, Col 1 and so on, up to Row 3, Col 3. Notice that the column changes fastest and the row changes slowest.} (indented four spaces) closes the inner loop. After it, control returns to the outer loop, which increases row and starts the inner loop again.} at the left margin closes the outer loop. When row becomes 4, the outer condition is false and the whole nested loop is finished.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);
}
let i = 0; creates the counter outside the loop. Because it is declared here, it will still exist after the loop ends.for (; i < 3; i++) { the first part, before the first semicolon, is left empty. This is allowed, because the counter was already created on line 1. The semicolon must still be written so that JavaScript knows which part is which. The condition i < 3 and the update i++ work exactly as usual.console.log(i); prints the counter on each pass. The output is 0, 1, 2.} ends the loop body. When the loop finishes, i is 3, and because it was declared outside the loop, you could still use it after the loop.
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.");
// is a comment. JavaScript ignores it completely. This comment warns the reader that the commented code below is an example of an infinite loop.i starts at 0, the condition is i >= 0 and the update is i++. Because i only ever increases, i >= 0 is always true. The // at the start turns the line into a comment so that it does not run.i forever. It is also commented out.// marks and run this in the editor, as it would freeze the browser tab.Always make sure your loop's condition can become false. The double-quoted string can contain an apostrophe (in loop’s) without any problem.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);
}
const colors = ["red", "green", "blue"]; creates an array with three items. Both loops below will go through this same array.// comment that labels the next loop as the classic index-based for loop. It is ignored by JavaScript.for (let i = 0; i < colors.length; i++) { creates an index i that goes through 0, 1 and 2, the valid positions in the array. You control the start, the end and the step.colors[i] gets the item at index i and console.log prints it: red, green, blue.} closes the classic for loop.for...of loop, which works with the values directly.for (const color of colors) { takes the array items one at a time and puts each in the variable color: first "red", then "green", then "blue". There is no counter, no condition and no update to write. const is fine, because a new color variable is created for every pass.console.log(color); prints the current item. You use color directly instead of colors[i], which is shorter and harder to get wrong.} ends the second loop. Both loops print the same thing, so the full output is red, green, blue and then red, green, blue again.
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);
const numbers = [10, 20, 30, 40, 50]; creates an array of five numbers. Their sum is what we want to calculate.let total = 0; creates a variable to collect the sum, starting at 0. It uses let (not const), because its value will change during the loop.for (let i = 0; i < numbers.length; i++) { visits each index of the array, 0 to 4, so every number is used exactly once.total += numbers[i]; is shorthand for total = total + numbers[i];. On each pass the current number is added to the total, which grows like this: 10, 30, 60, 100 and finally 150.} ends the loop body. After the fifth pass i becomes 5, the condition fails and the loop ends.Total: 150.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
varinstead ofletfor 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
continueskips to the next iteration rather than exiting the loop entirely.
Best Practices for for Loops
- Use
letfor the loop counter instead ofvar. - Cache
array.lengthin a variable if it’s expensive to compute and won’t change during the loop. - Use
for...ofwhen 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
forloop has three parts: initializer, condition, and update expression. - The loop runs as long as the condition remains
true. breakexits the loop immediately;continueskips to the next iteration.forloops can be nested to work with grids or multi-dimensional data.- An incorrect or missing condition can cause an infinite loop.
for...ofandfor...inoffer 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);
}
let i = 0 or let i = 10), a different end (i <= 10), or a different step (i += 2 to count by twos, or i-- together with a starting value of 5 and a condition of i >= 1 to count down). Click Test My Code after every change and compare the output.console.log("Count:", i); prints the text and the current value of i on one line. With the original values the output is Count: 1 to Count: 5.} ends the loop body. Make sure the condition can eventually become false when you edit the loop, or it will run forever.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.
Click “Run Code” to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.