SKU // 78

JavaScript Loops: The Full Picture

You learned the loop statements back in the Loops section. Since then you have met strings, arrays, objects, Sets, and Maps. This lesson pulls it all together: for each kind of data, which loop fits best, and why.

// Every Way to Loop

Loop Gives you break / continue?
for (let i = 0; ...)A counter you controlYes
for...ofEach value of an iterableYes
for...inEach key of an objectYes
while / do...whileRepeats until a condition changesYes
array.forEach(fn)Each value (and index) of an arrayNo

// The Classic for, Piece by Piece

The classic for loop is the one to use when you know how many times to repeat. Its parentheses hold three expressions, separated by semicolons:

for (exp1; exp2; exp3) {
  // code block to be executed
}
exp1Runs once, before the loop starts (usually let i = 0)
exp2Checked before every pass; the loop stops when it is false
exp3Runs after every pass (usually i++)
for (let i = 0; i < 3; i++) {
  console.log("The number is " + i);
}
The number is 0 The number is 1 The number is 2

while checks its condition before each pass, so it may run zero times. do...while checks after, so its body always runs at least once, even if the condition starts out false.

Trap: the loop that never ends
A while or do...while loop only stops when something inside it makes the condition false. Forget the i++ and the condition stays true forever: the page freezes and the browser eventually offers to kill it. Before you run a loop, point to the line that moves it toward the finish.

let, const, or var in the loop header

In for...of and for...in, the loop variable can be declared with const, let, or var. const is the usual choice because each pass gets a brand-new variable. The classic for is different: it changes the same variable with i++, so it needs let:

for (const i = 0; i < 3; i++) { }
TypeError: Assignment to constant variable.

The body runs once with i as 0, then i++ tries to change a constant. Avoid var in loop headers: it leaks the variable outside the loop (see JS Scope).

// Arrays

const scores = [88, 92, 75];

for (const s of scores) { }                    // just the values: first choice
for (const [i, s] of scores.entries()) { }     // index AND value
for (let i = scores.length - 1; i >= 0; i--) { }  // backwards, or skipping around
scores.forEach((s, i) => { });                  // fine when you never need to stop early
for (const [i, s] of scores.entries()) {
  console.log(`#${i + 1}: ${s}`);
}
#1: 88 #2: 92 #3: 75

// Strings

for (const ch of "Hi!") {
  console.log(ch);
}
H i !

// Objects

Plain objects cannot go straight into for...of. Use Object.entries to get [key, value] pairs, or for...in for keys:

const stock = { pens: 40, tape: 6, glue: 0 };

for (const [item, qty] of Object.entries(stock)) {
  if (qty === 0) continue;
  console.log(`${item}: ${qty}`);
}
pens: 40 tape: 6
Tip
Object.entries with for...of is usually clearer than for...in: you get the value directly instead of writing stock[key], and you only see the object's own properties.
Trap: for...in on an array
for...in walks an object's enumerable properties: the keys you can see in a loop. On an array those keys are the indexes, but as strings: for (const k in ["a", "b"]) gives "0" and "1", so k + 1 is "01", not 1. Use for...of (or entries()) for arrays and keep for...in for objects.

// Sets and Maps

A Set hands for...of its values. A Map hands it [key, value] pairs, which you can destructure right in the loop header:

const tags = new Set(["js", "css"]);
for (const tag of tags) {
  console.log(tag);
}

const ages = new Map([["Ava", 16], ["Ben", 17]]);
for (const [name, age] of ages) {
  console.log(`${name} is ${age}`);
}
js css Ava is 16 Ben is 17

// When You Do Not Know How Many Times

let guesses = 0;
let n;
do {
  n = Math.floor(Math.random() * 10);
  guesses++;
} while (n !== 7);

console.log(`Rolled a 7 after ${guesses} tries`);

// Loop or Array Method?

If the goal is to build something from an array, the array methods from Array Iterations usually say it more clearly than a loop:

// Loop version
const passing = [];
for (const s of scores) {
  if (s >= 80) passing.push(s);
}

// Method version: same result, one line
const passing2 = scores.filter(s => s >= 80);

console.log(passing, passing2);
[88, 92] [88, 92]

Array methods like forEach(), map(), filter(), and reduce() are often shorter and clearer than a loop for array work. The one thing they cannot do is stop early:

scores.forEach(s => {
  if (s > 90) break;   // not allowed here
});
SyntaxError: Illegal break statement

break and continue only work inside a real loop, and the arrow function is not one. When you might need to stop, use for...of.

// Decision Guide

  1. Transforming, filtering, or totaling an array? Use map / filter / reduce
  2. Visiting each value of an array, string, Set, or Map? Use for...of
  3. Visiting an object's properties? Use for...of over Object.entries(obj)
  4. Need a counter, a step size, or to go backwards? Use a classic for
  5. Waiting for something to happen? Use while

// Quick Check

In for (let i = 0; i < 5; i++), when does i++ run?

  1. Once, before the loop starts
  2. Before every pass, as part of the check
  3. After every pass through the body
  4. Only when i < 5 is false
Show answer
C. The third expression runs after each pass. The first runs once at the start, and the middle one is the check before each pass.

What does this log?

let n = 10;
do {
  console.log(n);
} while (n < 5);
Show answer
10. The condition is false from the start, but do...while runs its body once before checking. A plain while would log nothing.

You need to search an array and stop as soon as you find a match. Which should you use?

  1. forEach
  2. for...in
  3. for...of with break
  4. map
Show answer
C. forEach and map cannot break (it is a SyntaxError), and for...in gives string indexes, not values. (find() from Array Search also works.)

// Try It

  1. Click Open Playground and run it. Add two more scores and run it again
  2. Loop over an object of test scores with Object.entries and print only the ones below 70
  3. Rewrite a forEach so it can stop early when it finds a certain value
  4. Take one task (like totaling prices) and solve it with a for loop, for...of, and reduce
// Video Walkthroughs
Last updated: Oct 10, 2026, 1:42 AM ET