A for loop runs the same block of code as long as its condition is true. That way, you don’t have to write the same statement over and over.
JavaScript has several kinds of loops. In this guide, I’ll walk through the for loop syntax, show some practical examples, and explain how to exit a loop early and which loop to use for arrays and objects.
The for Loop in JavaScript
A for loop keeps going until its condition evaluates to false. Everything that controls the loop fits on one line:
for (initialization; condition; afterthought) {
// loop body
}
“The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons”. MDN, for statement
Here’s what each part does:
- Initialization runs once, before the loop starts. This is usually where you declare a counter, as in
let i = 1. - Condition is what the loop checks before every iteration. If you leave it out, the loop treats it as true.
- Afterthought runs after every iteration. It’s usually where you update the counter, for example with
i++.
Here’s how that plays out:
- The initialization runs first and sets up the counter.
- The loop checks the condition. If it’s
false, the loop ends. - If it’s
true, the loop body runs. - Then the afterthought runs and updates the counter.
- The loop goes back to step 2.
You can follow the same cycle in the flowchart below:
JavaScript for Loop Examples
I’ll start with simple counting, then move on to arrays and form elements.
Example A
I’ll use a for loop to display a message 5 times.
Code:
// program to display text 5 times
const n = 5;
// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
console.log(`I love JavaScript.`);
}
Output:
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
Here’s a table that shows how the loop works in this case:
| Iteration | Variable | Condition: i <= n | Action |
|---|---|---|---|
| 1st | i = 1
n = 5 |
true |
I love JavaScript. is printed.
i is increased to 2. |
| 2nd | i = 2
n = 5 |
true |
I love JavaScript. is printed.
i is increased to 3. |
| 3rd | i = 3
n = 5 |
true |
I love JavaScript. is printed.
i is increased to 4. |
| 4th | i = 4
n = 5 |
true |
I love JavaScript. is printed.
i is increased to 5. |
| 5th | i = 5
n = 5 |
true |
I love JavaScript. is printed.
i is increased to 6. |
| 6th | i = 6
n = 5 |
false |
The loop is terminated. |
Example B
I’ll use a for loop here to display the numbers from 1 to 5.
Code:
// program to display numbers from 1 to 5
const n = 5;
// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
console.log(i); // printing the value of i
}
Output:
1
2
3
4
5
Here’s how the loop works:
| Iteration | Variable | Condition: i <= n | Action |
|---|---|---|---|
| 1st | i = 1
n = 5 |
true |
1 is printed.
i is increased to 2. |
| 2nd | i = 2
n = 5 |
true |
2 is printed.
i is increased to 3. |
| 3rd | i = 3
n = 5 |
true |
3 is printed.
i is increased to 4. |
| 4th | i = 4
n = 5 |
true |
4 is printed.
i is increased to 5. |
| 5th | i = 5
n = 5 |
true |
5 is printed.
i is increased to 6. |
| 6th | i = 6
n = 5 |
false |
The loop is terminated. |
Example C
This example uses a for loop to add up all the natural numbers from 1 to 100.
Code:
// program to display the sum of natural numbers
let sum = 0;
const n = 100;
// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
console.log('sum:', sum);
Output:
sum: 5050
In this loop, sum starts at 0. The counter i counts from 1 to 100, and each iteration adds its value to sum.
Once i reaches 101, the condition returns false and the loop stops. Now sum holds 1 + 2 + ... + 100.
You can also count down and get the same total:
// program to display the sum of natural numbers, counting down
let sum = 0;
const n = 100;
// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- ) {
// adding i to sum in each iteration
sum += i; // sum = sum + i
}
console.log('sum:', sum); // sum: 5050
Both versions print 5050. If two approaches give the same result, pick the one that’s easier to read.
Example D
You’ll work with arrays in JavaScript a lot. This example loops over one and splits it into even and odd numbers.
Code:
const numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
const evenNumbers = [];
const oddNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
} else {
oddNumbers.push(numbers[i]);
}
}
console.log("The even numbers are: " + evenNumbers); // "The even numbers are: 4,44,64,24,32,74,22"
console.log("The odd numbers are: " + oddNumbers); // "The odd numbers are: 1,55,55,19,17,23"
Example E
I adapted this example from MDN’s Loops and iteration guide. It uses a for loop to count the selected options in a select element that lets you pick more than one.
Here’s the HTML:
<form name="selectForm">
<label for="musicTypes">Choose some music types, then click the button below:</label>
<select id="musicTypes" name="musicTypes" multiple>
<option selected>R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
<button id="btn" type="button">How many are selected?</button>
</form>
Here’s what the JavaScript code looks like:
function howMany(selectObject) {
let numberSelected = 0;
for (let i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
const musicTypes = document.selectForm.musicTypes;
console.log(`You have selected ${howMany(musicTypes)} option(s).`);
});
The loop starts with i at 0. It runs once per option, with i++ on each iteration.
Only numberSelected depends on which options are selected. It goes up by 1 if the current option is selected.
Stop or Skip Iterations with break and continue
Sometimes you don’t need a loop to run all the way to the end. The break statement exits the loop, while the continue statement skips straight to the next iteration.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
console.log(i);
}
Output:
1
3
5
7
for vs for…of vs forEach vs for…in
The classic for loop isn’t always the easiest to read. This table shows when each option fits:
| Loop | Use it when | Supports break |
|---|---|---|
for | You need the index, a custom step, or a reverse order | Yes |
for...of | You need each value of an array, string, Map or Set | Yes |
forEach() | You want to run a function once per array item | No |
for...in | You need the property names of an object | Yes |
Here is the same array printed with for...of and with forEach():
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
colors.forEach((color) => console.log(color));
“There is no way to stop or break a forEach() loop other than by throwing an exception.” MDN, Array.prototype.forEach()
forEach() doesn’t wait for promises either. If you’re using await in a loop, see sequential vs parallel JavaScript.
Avoid for...in with arrays. It goes through property names, including any extra ones you’ve added to the array. If you need to check the condition after the loop body runs, use a do-while loop.
Common for Loop Mistakes
Most loop bugs come down to the condition, the counter or the variable declaration.
Off-by-One Errors
Array indexes start at 0, so the last index is length - 1. Use <= with length and you’ll read one item too many.
const letters = ['a', 'b', 'c'];
for (let i = 0; i <= letters.length; i++) {
console.log(letters[i]); // a, b, c, undefined
}
for (let i = 0; i < letters.length; i++) {
console.log(letters[i]); // a, b, c
}
Infinite Loops
If a loop’s condition never becomes false, the loop just keeps going. This one counts down while it waits to pass 10, so don’t run it:
for (let i = 0; i < 10; i--) {
// i only gets smaller
}
Using var Instead of let
With let, each iteration gets its own copy of the counter. Use var instead, and all the callbacks share the same variable.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i)); // 3, 3, 3
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j)); // 0, 1, 2
}
You can read more about JavaScript variables and constants.
FAQs
Here are short answers to common questions about the JavaScript for loop.
for loop repeats a block of code while a condition is true. It combines the counter setup, the condition and the counter update in one line.
break to leave the loop. Use continue to skip the rest of the current iteration and move to the next one.
for loop gives you full control over a counter. A for...of loop hands you each value directly, so there is no index to manage.
false. Check that the counter changes after each iteration and moves toward the limit in your condition.
for statement is part of the JavaScript language, so the same syntax runs in browsers and in Node.js.
Summary
A for loop sets up a counter, checks a condition, runs the body, and then updates the counter. Use it when you need that level of control.
If you’re just working with array values, for...of is usually easier to read. Either way, if something looks off, start by checking the loop’s end condition.
Got a question? Ask away in the comments.
