Thuta Learning
JavaScript
BasicProgrammingBeginner

JS For Loop

JavaScriptLesson 920 min

What you'll walk away with

  • Explain, in order, when each of the three parts of a for header runs
  • Avoid off-by-one errors by looping with i < array.length
  • Skip one pass with continue and stop the loop early with break
  • Choose a classic for when you need the index and for...of when you only need values

Explain it simply

Explain it simply

Imagine calling the roll for a class of 30 students. You start at the first name on the list, keep going while names remain, and move down one line after each name. You only need three rules: where to start, when to stop, and how to step forward after each turn.

JavaScript's for loop lets you write those three rules on a single line: for (let i = 0; i < 30; i++). Instead of copying the same code thirty times, you tell one block to run repeatedly. It is the everyday tool for handling the items of an array one by one.

Problem → Why → Solution

The problem: a loop that crashes on its last pass

This loop upper-cases product names and prints them. All three items come out correctly, and then the program dies with a TypeError. Worse, the code after the loop, such as the total calculation or the save step, never runs at all.

products.js
const products = ["pen", "book", "bag"];

for (let i = 0; i <= products.length; i++) {
  console.log(products[i].toUpperCase());
}
// PEN, BOOK, BAG, then:
// TypeError: Cannot read properties of undefined (reading 'toUpperCase')

Why does it run one time too many?

Array indexes start at 0, so a three-item array has indexes 0, 1 and 2. products.length is 3, and with i <= 3 the body also runs when i is 3. products[3] is undefined, and calling a method on undefined crashes. Writing i < products.length stops at the last valid index.

Core concept: the three parts and their order

The header for (initialization; condition; update) holds three parts separated by two semicolons. Once you know the order they run in, you can trace any loop in your head.

1. Initialization runs once

let i = 0 runs a single time, before anything else. This is where the counter variable is declared.

2. The condition is checked before every pass

If i < cars.length is true, the body runs; the moment it is false, the loop ends. If it is false on the very first check, the body never runs at all.

3. The update runs after the body

i++ runs after each pass of the body, and then the condition is checked again. That is why the first pass sees i as 0, not 1.

When walking an array, always use the i < array.length form, because the highest index is length - 1. The update does not have to be i++: i += 2 visits every other item and i-- counts backward. An i declared with let lives only inside the loop and gets a fresh binding on each pass, while var leaks out of the loop, so use let.

Inside the body, break stops the whole loop immediately, and continue skips the rest of the current pass and jumps straight to the update. When you need the values but not the index, for (const car of cars) with for...of is shorter and cannot go off by one. Remember too that the body runs once per item, so the loop's running time grows with the array.

You can place one loop inside another, a nested loop, for example to visit every column of every row in a table. The inner loop runs from start to finish on each pass of the outer loop, so 100 rows by 100 columns means the body runs 10,000 times. Give the counters different names, such as i and j.

Mental model: start, check, run, step
  1. Run initialization once
  2. Check condition; false means exit
  3. Run the body
  4. Run update, then check again

The update runs after the body, so the first pass always sees the initial value.

General pattern

javascript
for (let i = start; i < end; i++) {
  // use i here
}

for (let i = 0; i < list.length; i++) {
  // list[i] is the current item
}

for (const item of list) {
  // only the value, no index
}

The first shape repeats a known number of times, the second walks an array by index, and the third is for...of when you only need the values.

Example: walking a car array by index

This loop walks a four-item array with a classic for loop and prints each index next to its value. Printing the index makes it visible that counting starts at 0.

cars.js
const cars = ["BMW", "Volvo", "Saab", "Ford"];

for (let i = 0; i < cars.length; i++) {
  console.log(i + ": " + cars[i]);
}

console.log("Loop ran " + cars.length + " times");

Code breakdown

  1. Line 3for (let i = 0; i < cars.length; i++) {

    i starts at 0 and continues while it is less than cars.length (4), so it takes the values 0, 1, 2 and 3 and stops at 4.

  2. Line 4console.log(i + ": " + cars[i]);

    cars[i] is the item for the current pass: "BMW" when i is 0 and "Ford" when i is 3.

  3. Line 3 (update)i++

    Reaching the end of the body triggers i++ and a fresh condition check. At i = 4, 4 < 4 is false and the loop ends.

  4. Line 7console.log("Loop ran " + cars.length + " times");

    Runs once, after the loop. The body ran once per item, four times in total.

You should see
0: BMW
1: Volvo
2: Saab
3: Ford
Loop ran 4 times
One trip around a for loop
  1. let i = 0 (once)
  2. Check i < cars.length
  3. Run the body
  4. i++, then check again

Condition is true

run the body again

Condition is false

leave the loop

break, continue and for...of

This snippet skips free or negative prices with continue and stops with break at the first item above 20. The second loop needs no index, so it uses for...of, and the third counts backward with i--.

break-continue.js
const prices = [12, 0, 7, -3, 25, 9];

for (let i = 0; i < prices.length; i++) {
  if (prices[i] <= 0) continue; // skip free or invalid items
  if (prices[i] > 20) break;    // stop at the first expensive item
  console.log("Index " + i + " costs " + prices[i]);
}

let sum = 0;
for (const price of prices) {
  sum += price;
}
console.log("Sum of all prices: " + sum);

for (let n = 3; n > 0; n--) {
  console.log("Countdown " + n);
}

The first loop prints only Index 0 and Index 2. Index 4 holds 25, which triggers break, so Index 5 (9) is never reached.

In real projects

Where for loops show up in real projects

Reports and dashboards often walk the data once and collect several statistics along the way. For example, one pass over an array of student scores can produce the total, the count and the highest score together. One pass instead of three is noticeably faster as data grows. Invalid scores, such as negatives or strings, are skipped with continue, and you must decide in advance what an empty array should return.

Where the index itself matters, the classic for is essential: numbering table rows, comparing neighbouring items such as prices[i] and prices[i - 1] to compute a price change, or jumping with i += 100 to send data to a server in batches of 100. For plain transformation or selection, most projects prefer map and filter, which the arrays lesson covers.

Common mistakes

Common mistakes

1. Writing i <= array.length

As the problem section showed, this goes one position past the end and reads undefined. Use < for array indexes, or for...of when you do not need the index.

2. Removing items while looping forward

Calling splice(i, 1) inside a forward loop shifts every later item one place left, and i++ then skips the item that moved into position i. Removing the 2s from [1, 2, 2, 3] this way leaves one 2 behind. Loop backward, or build a new array with filter.

3. Using var instead of let

With for (var i = 0; ...), i survives after the loop and every pass shares one variable. Printing i inside a setTimeout in that loop gives 3, 3, 3 instead of 0, 1, 2. let creates a fresh i for each pass, so the problem disappears.

Best practices

Best practices

  • Declare the loop counter with let and do not try to reuse i after the loop.
  • Pick for...of when you do not need the index; a whole class of off-by-one bugs disappears.
  • Before writing a loop, work out what i is on the first pass and on the last pass.
  • When the body fills with conditions, skip invalid cases early with continue and keep the main logic at a shallow indentation.

Mini challenge

Mini challenge: summarize scores

Write summarizeScores(), which walks a score array with a single classic for loop and returns the count, total, highest and average.

  • Use exactly one loop, in the i < scores.length form
  • Skip non-numbers and negative scores with continue, printing a message with the index
  • Return null when there are no valid scores
  • Return a { count, total, highest, average } object
scores.js
function summarizeScores(scores) {
  // TODO: set up count, total and highest

  for (/* TODO: index loop over scores */) {
    // TODO: skip invalid scores with continue (print the index)
    // TODO: update count, total and highest
  }

  // TODO: return null when nothing was valid, otherwise the summary object
}

console.log(summarizeScores([72, 95, -1, 88]));
console.log(summarizeScores([]));

Expected: Skipping invalid score at index 2 { count: 3, total: 255, highest: 95, average: 85 } null

Show hint

Start highest at -Infinity so the first valid score always beats it. After the loop, check whether count is still 0 and return null if so.

Show solution
scores.js
function summarizeScores(scores) {
  let count = 0;
  let total = 0;
  let highest = -Infinity;

  for (let i = 0; i < scores.length; i++) {
    const score = scores[i];
    if (typeof score !== "number" || score < 0) {
      console.log("Skipping invalid score at index " + i);
      continue;
    }
    count++;
    total += score;
    if (score > highest) highest = score;
  }

  if (count === 0) return null;
  return { count, total, highest, average: total / count };
}

console.log(summarizeScores([72, 95, -1, 88]));
console.log(summarizeScores([]));

Quick quiz 1 / 3

What does for (let i = 10; i > 0; i -= 3) console.log(i); print?

Quick quiz 2 / 3

What happens with const arr = ["a", "b", "c"]; for (let i = 0; i <= arr.length; i++) console.log(arr[i].toUpperCase());?

Quick quiz 3 / 3

What does for (let i = 1; i <= 5; i++) { if (i === 3) continue; if (i === 5) break; console.log(i); } print?

What to remember

  • The order is: initialization once, check the condition, run the body, run the update.
  • Use i < array.length for indexes; the highest index is length - 1.
  • continue skips one pass, while break ends the whole loop.
  • Use for...of when you do not need the index, and always declare the counter with let.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS For Loop | Thuta Learning