Computers are very good at doing repetitive work without getting bored. A loop repeats a block of code ten times, a thousand times, or once for every item in a list. The for loop is the loop you'll use most often.
Loops are what let a few lines of code handle any amount of data. Whether a shop has three products or three thousand, the same loop can display each one, add up the prices or find the cheapest. Once you're comfortable with loops, you can start working with real lists of information.
The classic for loop
for (let i = 1; i <= 5; i++) {
console.log("Lap", i);
}The brackets contain three parts, separated by semicolons:
- Start:
let i = 1runs once, before the loop begins. - Condition:
i <= 5is checked before every lap. When it becomes false, the loop stops. - Update:
i++runs after every lap.
i, short for index, is the traditional name for the counter. The classic loop is the right choice when you need the position number, want to count backwards, or want to skip items, such as every second one.
for...of: once for every item
To go through every value in an array, or every character in a string, for...of is the simplest option:
for (const fruit of ["apple", "kiwi", "fig"]) {
console.log(fruit);
}There's no counter to manage, so there are no off-by-one errors. Read it as "for each fruit of this list".
for...in: looping over object keys
for...in loops over the keys (property names) of an object:
for (const key in settings) {
console.log(key, settings[key]);
}Don't use for...in on arrays. It loops over the positions as strings and can include unexpected extra properties. Use for...of for arrays instead.
break and continue
breakstops the loop completely. It's useful once you've found what you were searching for.continueskips the rest of the current lap and moves on to the next one. It's useful for ignoring items you don't need, such as empty values.
JavaScript for Loop Syntax
for loops
for (let i = 0; i < 10; i++) { }
for (const item of array) { }
for (const key in object) { }JavaScript for Loop Summary
- A loop repeats a block of code.
- The classic
forloop has a start, a condition and an update. for...ofvisits every item in an array or string.for...invisits the keys of an object; don't use it on arrays.breakexits a loop early andcontinueskips to the next lap.
JavaScript for Loop Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Counting and stepping
for (let i = 1; i <= 5; i++) {
console.log("Lap", i);
}
for (let i = 10; i > 0; i -= 3) {
console.log("Countdown:", i);
}
console.log("Liftoff! 🚀");Line-by-line explanation
- Line 1Start at 1, keep going while i ≤ 5, add 1 each time.
- Line 5Start at 10, count down by 3: 10, 7, 4, 1.
- Line 9Runs once the loop has finished.
Looping over an array
const playlist = ["Levitating", "Blinding Lights", "Shape of You"];
for (let i = 0; i < playlist.length; i++) {
console.log(`${i + 1}. ${playlist[i]}`);
}
let totalLetters = 0;
for (const song of playlist) {
totalLetters += song.length;
}
console.log("Total letters:", totalLetters);Line-by-line explanation
- Line 3Classic loop using the index.
i < playlist.lengthstops at the last index. - Line 4
i + 1turns index 0 into track number 1. - Lines 8 to 10
for…ofwhen you only need the values.
break, continue and nested loops
const numbers = [4, 7, -2, 9, 0, 12];
for (const n of numbers) {
if (n < 0) continue; // skip negatives
if (n === 0) break; // stop at zero
console.log("Processing", n);
}
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line += row * col + "\t";
}
console.log(line);
}Line-by-line explanation
- Line 4
continueskips -2 but keeps looping. - Line 5
breakstops everything at 0, so 12 is never processed. - Lines 9 to 15A loop inside a loop builds a 3×3 times table.
Common JavaScript for Loop Mistakes
Off-by-one with <=
const colors = ["red", "green", "blue"];
for (let i = 0; i <= colors.length; i++) {
console.log(colors[i]); // last one is undefined
}for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}Indexes go from 0 to length - 1, so use <, not <=.
A loop that never ends
for (let i = 0; i < 10; i--) { … } // i goes down foreverfor (let i = 0; i < 10; i++) { … }If the condition never becomes false, the page freezes. On Codevra, a safety net stops loops after 1.5 seconds.
Using for…in on arrays
for (const x in ["a", "b"]) console.log(x); // "0", "1" (strings!)for (const x of ["a", "b"]) console.log(x); // "a", "b"JavaScript for Loop in Real Projects
Loops power lists
Displaying a list of products, sending a reminder to every customer, adding up an order total, checking every field in a form and drawing the squares on a game board all use loops. In modern code you'll often use array methods like map and filter instead (see Array Methods), but they're loops underneath.
JavaScript for Loop Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Log the numbers 1 to 3.
for (let i = 1; i 3; ) {
console.log(i);
}
What does this print?
for (let i = 0; i < 3; i++) {
console.log(i * 2);
}How many times does "Hi" print?
for (let i = 10; i > 0; i -= 2) {
console.log("Hi");
}This should log every guest's name in capitals, but it logs undefined at the end and crashes. Fix the loop.
const guests = ["ana", "ben", "cleo"];
for (let i = 0; i <= guests.length; i++) {
console.log(guests[i].toUpperCase());
}- Logs the three names in capitals
- No errors
JavaScript for Loop Quiz
3 questions to check what you learned.
Which loop is simplest for going through every item of an array?
- for…in
- while
- switch
- for…of
What does
continuedo inside a loop?- Stops the loop
- Restarts the loop from the beginning
- Skips to the next iteration
- Pauses for a second
For an array of length 5, what is the last valid index?
- 4
- 5
- 6
- -1
JavaScript for Loop Challenge
Shopping total
Use a loop to add up the prices:
- Loop over
pricesand add each tototal - Count how many items cost more than 5 in
expensiveCount - Log
Total: 31.5andExpensive items: 2
const prices = [3.5, 12, 4, 9.5, 2.5];
let total = 0;
let expensiveCount = 0;
- total is 31.5
- expensiveCount is 2
- Logs both lines
- Uses a loop