JS Loops (for, while, forEach): Beginner Guide

JS Loops (for, while, forEach): Beginner Guide

Imagine printing a certificate for 200 students by typing each name by hand. You would never do that; you would repeat one step 200 times. That is the whole idea behind JS loops: run the same block of code again and again, with a different value each time, until a condition says stop.

JavaScript has several kinds of loops, and picking the right one makes code shorter and clearer. This guide covers each of them with the output shown. You will need to know variables and a little about conditions.

The classic for loop

A for loop has three parts in the parentheses: where to start, when to keep going, and how to step.

for (let i = 1; i <= 5; i++) {
  console.log("Round", i);
}
// Round 1
// Round 2
// Round 3
// Round 4
// Round 5
  1. let i = 1 runs once at the start.
  2. i <= 5 is checked before every round. If it is false, the loop ends.
  3. i++ runs after every round and adds one to i.

Use a for loop when you know how many times to repeat, or when you need the counter itself. The ++ and <= symbols are covered in our guide to JavaScript operators.

The while loop

A while loop keeps going as long as its condition is true. It is the better choice when you do not know in advance how many rounds you need.

let money = 100;
let months = 0;

while (money < 200) {
  money = money * 1.1; // grows 10% each month
  months++;
}

console.log(months); // 8

The loop runs eight times because 100 grows to about 214 after eight rounds at 10%. The variable you test (money) must change inside the loop, otherwise the condition never turns false.

do...while runs at least once

A do...while loop checks the condition after the body, so the body always runs one time. It suits "try, then ask again" situations such as showing a menu.

let tries = 0;
do {
  tries++;
  console.log("Attempt", tries);
} while (tries < 2);
// Attempt 1
// Attempt 2

for...of: the friendliest way to read an array

When you just want each item from a list, for...of hides the counter.

const colors = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color.toUpperCase());
}
// RED
// GREEN
// BLUE

It also works on strings and other iterable things. If lists are new to you, read about JS arrays first.

Related reading: JavaScript Functions Explained for Beginners: Complete Guide

for...in: keys of an object

Use for...in to go through the keys of an object.

const user = { name: "Asha", city: "Pune" };

for (const key in user) {
  console.log(key, "=", user[key]);
}
// name = Asha
// city = Pune

Avoid for...in on arrays. It gives you the indexes as text, and it can include extra inherited properties. For arrays, stick with for...of.

forEach: a method with a callback

Arrays have a built-in forEach method that calls a function for every item.

const scores = [80, 92, 67];

scores.forEach((score, index) => {
  console.log(`Student ${index + 1}: ${score}`);
});
// Student 1: 80
// Student 2: 92
// Student 3: 67

It reads nicely, but it has two limits: you cannot stop it early with break, and it does not wait for asynchronous code inside the callback. If you need either, use for...of. If you want a new array back, use map or filter instead of forEach.

break and continue

Two keywords let you steer a loop from the inside:

  • break leaves the loop completely.
  • continue skips the rest of this round and jumps to the next one.
for (let n = 1; n <= 10; n++) {
  if (n % 2 === 0) continue; // skip even numbers
  if (n > 7) break;         // stop after 7
  console.log(n);
}
// 1
// 3
// 5
// 7

Loops inside loops

You can place one loop inside another. The inner loop runs completely for every single round of the outer loop, which is handy for grids, tables and combinations.

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += row * col + " ";
  }
  console.log(line.trim());
}
// 1 2 3
// 2 4 6
// 3 6 9

That prints a small multiplication table. Keep an eye on the cost: three rounds times three rounds is nine runs, but 1,000 times 1,000 is a million, so nested loops over big lists can slow a page down.

Which loop should you use?

  • for: you know the count, or need the index.
  • while: you repeat until something changes.
  • for...of: you want every item from an array or string.
  • for...in: you want the keys of an object.
  • forEach: you like callbacks and do not need break.

Common mistakes

  • Infinite loops. Forgetting to update the counter, for example leaving out i++, makes the loop run forever and freezes the tab. Close the page or stop Node with Ctrl+C.
  • Off-by-one errors. Using i <= arr.length instead of i < arr.length reads one item past the end and gives undefined.
  • Changing an array while looping over it, which can skip items.
  • Using var in loops where callbacks capture the variable. Use let or const; the reason is explained in JS scope and hoisting.

When a loop does something strange, add a console.log of the counter at the start of the body. More lessons like this are in the JavaScript category.

Conclusion

Loops save you from repeating yourself. Remember:

  • A for loop has a start, a condition and a step.
  • A while loop repeats until its condition is false, so something inside must change.
  • for...of is the simplest way to read each array item.
  • forEach is neat, but you cannot break out of it.
  • Check for infinite loops and off-by-one errors when things go wrong.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Your comment will appear after moderation.