Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

JavaScript Loops

Learn repetition in JavaScript: for and while, for...of over values and for...in over keys, break and continue, and when the array methods replace the loop entirely.

Levels: Beginner ~14 min read

Basic

JavaScript has more loop syntaxes than it strictly needs, a relic of thirty years of accretion, and part of fluency is simply ranking them. The classic for with its three clauses is the veteran. while repeats on a condition. for...of walks values and is the modern default. for...in walks property names and is the one most often used by mistake. And half the loops you would have written in an older language are better written today as forEach or map calls. Choosing well is a small decision you make hundreds of times, so it pays to make it consciously once.

for and while: the veterans

javascript classics.js
1
2
3
4
5
6
7
8
for (let i = 0; i < breads.length; i += 1) {
  console.log(breads[i]);
}

let loaves = 3;
while (loaves > 0) {
  loaves -= 1;
}

The counter loop, and the condition loop.

The three clauses of for are initialize, test, update, separated by semicolons and run in that order around each pass. Declare the counter with let, never var, so it stays inside the loop. The classic for earns its place when the index itself matters, stepping by two, walking two arrays in step, stopping at particular positions, and cedes the rest to for...of. The while loop's contract is unchanged across languages: something in the body must move the condition toward false, or the loop simply never ends.

for...of and for...in: values versus names

for...of walks the values of anything iterable, arrays, strings, and hands each one to your variable directly, no counter, no bracket access. It is the loop you reach for first. Its near-namesake for...in walks the property names of an object, keys as strings, and using it on an array is the classic mistake: it works, mostly, walking the indexes as strings, "0", "1", and also any extra properties anyone attached, in an order with fine print. The mnemonic is the language's own cruelty: of iterates values, in iterates names, and only one of them belongs near an array.

javascript of-in.js
1
2
3
4
5
6
7
8
for (const bread of ["sourdough", "rye"]) {
  console.log(bread);        // the values
}

const loaf = { name: "rye", price: 38 };
for (const key in loaf) {
  console.log(key, loaf[key]);  // the property names
}

of for values; in for object keys.

break, continue, and labeled exits

break leaves the loop, continue skips to the next pass, both familiar and both best used near the top of the body as guards rather than buried mid-block. One addition JavaScript makes: a label before an outer loop lets break outer leave a nested loop from the inside, a feature that reads odd enough that a small flag variable or a well-named function usually wins instead.

When not to loop at all

The array methods already met in the arrays lesson are loop replacements, and the choice is about intent. Transforming every element is map, selecting is filter, accumulating is reduce, and doing a side effect per element is forEach. Each names its purpose in the call, needs no counter, and composes into pipelines. The loops keep the jobs with real control flow, breaking early from a search, interleaving steps, waiting on something, and the honest habit is the reverse of instinct: start from the method, and write the loop only when a loop's shape actually fits.

Match the shape to the job, and the loop question answers itself.

The job

The shape that says it

Transform every element

items.map(fn)

Keep some elements

items.filter(fn)

Collapse to one value

items.reduce(fn, start)

Do something per element

items.forEach(fn)

Find the first match

items.find(fn), then stop

Leave a loop mid-search

for...of with break

Walk two arrays in step

Classic for with one counter

Run the morning

The example below runs one bakery morning in all the loop shapes, printing to the preview console. Run it, then convert each loop to the shape that should own it: the numbered queue printed by the classic for is there because the position is part of the message; the batch walk is for...of with a continue guard; and the search loop uses break the moment it finds its bread. Then try the classic mistake: replace for...of on the batch with for...in and watch the items arrive as string indexes, including any a stray line of code attaches.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • Each loop shape had a job the others would have done worse: guarding, numbering, searching, conditioning.

  • The search stopped at its break; nothing past the find was ever walked.

  • The final menu line was never a loop at all, and map said so in one call.


Quick check

If you can choose between for...of and for...in without flinching, explain which jobs belong to the array methods instead, and write a while loop whose condition you know will turn, repetition is a choice you make on purpose. That completes the JavaScript path: variables, numbers, strings, decisions, functions, arrays, objects, and loops to walk them. Revisit any lesson through the JavaScript learning page, and close the path out with the JavaScript Loops quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.