JavaScript for Loops

Repeat code a set number of times or once for every item.

Lesson 14 of 56Beginner13 min read

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

JavaScript
for (let i = 1; i <= 5; i++) {
  console.log("Lap", i);
}

The brackets contain three parts, separated by semicolons:

  1. Start: let i = 1 runs once, before the loop begins.
  2. Condition: i <= 5 is checked before every lap. When it becomes false, the loop stops.
  3. 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:

JavaScript
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:

JavaScript
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

  • break stops the loop completely. It's useful once you've found what you were searching for.
  • continue skips 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 for loop has a start, a condition and an update.
  • for...of visits every item in an array or string.
  • for...in visits the keys of an object; don't use it on arrays.
  • break exits a loop early and continue skips to the next lap.

JavaScript for Loop Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

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! 🚀");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1Start at 1, keep going while i ≤ 5, add 1 each time.
  2. Line 5Start at 10, count down by 3: 10, 7, 4, 1.
  3. Line 9Runs once the loop has finished.
Example 2

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Classic loop using the index. i < playlist.length stops at the last index.
  2. Line 4i + 1 turns index 0 into track number 1.
  3. Lines 8 to 10for…of when you only need the values.
Example 3

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);
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 4continue skips -2 but keeps looping.
  2. Line 5break stops everything at 0, so 12 is never processed.
  3. Lines 9 to 15A loop inside a loop builds a 3×3 times table.

Common JavaScript for Loop Mistakes

Off-by-one with <=

Don't
const colors = ["red", "green", "blue"];
for (let i = 0; i <= colors.length; i++) {
  console.log(colors[i]); // last one is undefined
}
Do
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

Don't
for (let i = 0; i < 10; i--) { … } // i goes down forever
Do
for (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

Don't
for (const x in ["a", "b"]) console.log(x); // "0", "1" (strings!)
Do
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.

Fill in the blankseasy

Log the numbers 1 to 3.

for (let i = 1; i  3; ) {
  console.log(i);
}
Predict the outputeasy

What does this print?

for (let i = 0; i < 3; i++) {
  console.log(i * 2);
}
Predict the outputmedium

How many times does "Hi" print?

for (let i = 10; i > 0; i -= 2) {
  console.log("Hi");
}
Fix the bugmedium

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());
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs the three names in capitals
  • No errors

JavaScript for Loop Quiz

3 questions to check what you learned.

  1. Which loop is simplest for going through every item of an array?

    • for…in
    • while
    • switch
    • for…of
  2. What does continue do inside a loop?

    • Stops the loop
    • Restarts the loop from the beginning
    • Skips to the next iteration
    • Pauses for a second
  3. 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:

  1. Loop over prices and add each to total
  2. Count how many items cost more than 5 in expensiveCount
  3. Log Total: 31.5 and Expensive items: 2
const prices = [3.5, 12, 4, 9.5, 2.5];
let total = 0;
let expensiveCount = 0;
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • total is 31.5
  • expensiveCount is 2
  • Logs both lines
  • Uses a loop