In short
A JavaScript for loop repeats a block of code a set number of times. Learn the three parts of a for loop, how to count up and down, and how to loop through strings. What is a loop in JavaScript? A loop is a way to run the same code again and again without writing it again and again.
A JavaScript for loop repeats a block of code a set number of times. Learn the three parts of a for loop, how to count up and down, and how to loop through strings.
What is a loop in JavaScript?
A loop is a way to run the same code again and again without writing it again and again. Think of a teacher who says "do 10 jumping jacks". She does not say "jump" ten times. She gives one instruction and a number.
Without a loop, printing the numbers 1 to 5 looks like this:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
This works, but imagine doing it for 1,000 numbers. A loop does the same job in three lines, and it is just as easy for 5 numbers as for 5,000.
The three parts of a for loop
A for loop has three parts inside the round brackets, separated by semicolons:
- Start (initialization): create a counter variable, for example
let i = 1. This runs once, before the loop begins. - Condition: a test such as
i <= 5. Before each round, JavaScript checks it. If it istrue, the code runs. If it isfalse, the loop stops. - Step (update): change the counter after each round, for example
i++, which means "add 1 toi".
for (let i = 1; i <= 5; i++) {
console.log(`Lap number ${i}`);
}
// Output:
// Lap number 1
// Lap number 2
// Lap number 3
// Lap number 4
// Lap number 5
Here is what happens. let i = 1 creates the counter. JavaScript checks 1 <= 5, which is true, so it prints "Lap number 1". Then i++ makes i equal to 2, and the check runs again. When i becomes 6, the condition 6 <= 5 is false and the loop ends. Each single run of the loop body is called an iteration.
Note: Programmers often name the counter
i(short for "index"). You can use any name, likelaporcount, if it makes your code clearer.
How to count down with a for loop
To count backwards, start high, check that the counter is still big enough, and subtract with i-- (subtract 1).
for (let i = 5; i >= 1; i--) {
console.log(i);
}
console.log("Lift off!");
// Output: 5, 4, 3, 2, 1 (each on its own line), then "Lift off!"
You can also step by more than 1. i += 2 adds 2 each time, so for (let i = 0; i <= 10; i += 2) gives you the even numbers 0, 2, 4, 6, 8, 10.
How to loop through a string or an array
A string has a length property and each character has a position number called an index. Indexes start at 0, not 1. So the first letter of "Hello" is at index 0 and the last is at index 4.
const word = "Hello";
for (let i = 0; i < word.length; i++) {
console.log(`Letter ${i}: ${word[i]}`);
}
// Output:
// Letter 0: H
// Letter 1: e
// Letter 2: l
// Letter 3: l
// Letter 4: o
word.length is 5, so the condition i < word.length stops the loop after index 4. word[i] reads the character at position i.
An array is a list of values inside square brackets. You will learn arrays properly in the Arrays module, but they work the same way as strings here: they have a length and indexes that start at 0.
const groceries = ["milk", "bread", "eggs", "apples"];
for (let i = 0; i < groceries.length; i++) {
console.log(`${i + 1}. ${groceries[i]}`);
}
// Output:
// 1. milk
// 2. bread
// 3. eggs
// 4. apples
We print i + 1 so the list starts at 1 for humans, while groceries[i] still uses the real index starting at 0.
Common mistake: Writing
i <= word.lengthinstead ofi < word.length. The last index is alwayslength - 1, so<=goes one step too far and gives youundefined.
Example: build a multiplication table
Loops are great for anything with a pattern. Here is the 7 times table:
const number = 7;
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
// Output:
// 7 x 1 = 7
// 7 x 2 = 14
// ...
// 7 x 10 = 70
Change number to any value and you get a new table. This is the power of loops: one small change, a whole new result.
How to avoid infinite loops
An infinite loop is a loop that never stops, because its condition never becomes false. It can freeze your browser tab.
// Do NOT run this: i never changes, so i <= 5 is always true
// for (let i = 1; i <= 5; ) {
// console.log(i);
// }
To stay safe, always check three things: the counter starts at the right value, the condition can become false, and the step moves the counter toward that point. Counting up with i-- or counting down with i++ are classic causes of infinite loops.
Tip: If your tab freezes, close it and open a new one. Then look at the step part of your loop first.
You can read more on MDN's for statement page.
Practice exercise
Write a for loop that prints every number from 1 to 20, but next to each one write "even" or "odd", for example 4 is even. Then print the total of all the numbers from 1 to 20 after the loop.
Hint: Use the remainder operator %. If i % 2 === 0, the number is even. For the total, create let total = 0; before the loop and add i to it inside the loop.
Key takeaways
- A loop runs the same code many times, so you do not repeat yourself.
- A for loop has three parts: start, condition and step.
- Strings and arrays have indexes that start at 0, so loop while
i < length. - Use
i--to count down andi += 2(or any number) to take bigger steps. - Make sure the condition can become false, or you will create an infinite loop.
Frequently asked questions
Why does the for loop start at 0 so often?
Because strings and arrays start counting their positions at 0. Starting your counter at 0 means i matches the index of each item directly.
Can I use const in a for loop counter?
Not for a normal counting loop. The counter changes with i++, and a const variable cannot change, so you will get an error. Use let.
What is the difference between i++ and i += 1?
In a for loop step, there is no difference. Both add 1 to i. i += 1 is useful when you want to change the step to another number later.