Stop copying the same code ten times: JavaScript loops — for, while, and for...of, explained plainly
A menu with six dishes does not need its price addition copied six times — one loop does it. Following MDN's Looping code, for, and for...of: the three parts of a for loop, for...of first with collections, choosing for only when you need the index, while and do...while, break and continue, for...in versus for...of, and the three traps of changing things inside a loop.

First, the boundaries of this guide. The site already has plenty of JavaScript basics guides: the functions guide covers how to write functions, the conditionals guide covers how to make decisions, array methods covers map, filter, and reduce, string methods covers text, numbers and Math covers arithmetic, and objects and destructuring, classes and prototypes, closures, the event loop, modules, Fetch, DOM, and localStorage each have their own guide. This one does not repeat them. It covers one thing only: loops. When you build a web page you repeat the same thing all day: a menu has six dishes and each one needs its price calculated; an order list has twenty orders and each one needs its status checked; a countdown runs from 10 to 0 and the page changes every second. The example here is the same fictional practice project as before: Greenstone Cafe, a small order page for a street-side coffee shop. Earlier guides used it to explain functions and decisions; this time it shows how an order page hands repetitive work to loops: adding up every dish on a table, finding the first sold-out drink, and serving queued orders one by one. Every operation, code sample, and number using it is invented to explain the idea, not a real record. All syntax and behavior of loops comes from three MDN official docs: Looping code, for, and for...of. Sources are in each article's meta info and evidence record. After reading this guide, you should be able to do four things: write for, while, do...while, and for...of; reach for for...of first when you have a collection; control a loop with break and continue; and know the three most common traps of changing things inside a loop. This guide does not cover the full use of map, filter, and reduce — that belongs to the array methods guide — and it does not cover async loops or generators, except for one mention of the closure trap in step 10.
Step 1: A loop is "the same thing, done many times"
The MDN Learn article opens with a reassuring fact: a loop is not a new idea, it is just writing code you would otherwise copy many times only once, and letting the computer run it many times. The example in the article draws 100 random circles: without a loop you would copy the circle-drawing code 100 times, but with a loop you write one for, for (let i = 0; i < 100; i++), and the code in the braces runs 100 times, drawing one circle at a random position each time. The random function is defined earlier and returns a whole number between 0 and the number given; each circle calls random(canvas.width) and random(canvas.height) to pick its position. MDN adds a very practical point: drawing 100 circles takes the same amount of code as drawing 1,000 or 10,000 — only one number changes. On the cafe order page, a loop means the same thing: a menu with six dishes does not need the price addition copied six times, it needs one loop that adds each dish's price into total; twenty orders do not need their status check written twenty times, they need one loop that looks at them one by one. The check for this step is simple: the moment you are about to write the same code a second time, stop and ask whether this is a job for a loop. If yes, write the loop; if no, copy it once and move on. What a loop saves is not typing, it is fixing mistakes: when the pricing rule changes, you change one place inside the loop, but with ten copies you must change ten places, and one missed place is a bug.
Step 2: The three parts of a for loop — start, condition, step
Jobs where you know how many times to run and jobs where you do not use different loops. When you know how many times, the usual choice is the for loop. MDN writes it as for (initializer; condition; final-expression): three parts inside the parentheses, separated by semicolons. The first part is the starting value, usually a counter like let i = 0. The second part is the condition that decides when to stop, usually an expression with a comparison operator. The third part is the expression that runs at the end of each round, usually adding one to the counter or subtracting one. The code in the braces runs once per round. MDN's squaring example is verified: for (let i = 1; i < 10; i++), computing i * i and building strings like "1 x 1 = 1" — the first round gives 1, the second gives 4, and the ninth gives "9 x 9 = 81"; when i becomes 10 the loop stops and prints Finished. Breaking the three parts down: let i = 1 starts the counter at 1, i < 10 keeps going while i is below 10, and i++ adds one to i after each round. The MDN for reference adds two details: first, all three parts are optional, so leaving them all out gives for (;;) — but then the body must stop the loop with break, or it never ends. Verified: for (let i = 0; ; i++) with if (i > 3) break runs 5 rounds, i from 0 to 4. Second, the counter must use let, because it is reassigned every round — MDN states this explicitly as the reason let is required. On the cafe order page, a for loop fits "you know how many times" best: a countdown from 10 to 0 could use while, but with for the start, condition, and step all sit in the parentheses, visible at a glance. The check for this step: before writing a for loop, write the three parts down on paper — what is the start, when does it stop, how much does each round add. If any one of them is unclear, the loop may run one round too many or never stop.
Step 3: for...of — when you have a collection, reach for it first
Often a loop is not about counting, but about doing the same thing to every item in a collection: every dish in a menu array, every order in an orders array, every character in a string. That is when MDN recommends for...of first. It reads for (const cat of cats): take the items of cats one by one, hand each one to cat, and run the code in the braces for every cat. MDN's cats example is verified: cats is ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"], and for...of prints all six names, none missing. The advantage of for...of is "no counting": no worrying about which index to start at, where to stop, or how much to add each round, so there is nothing to count wrong. The MDN for...of reference also lists what it can handle: arrays, strings, Maps, and Sets all work. Verified: the string "boo" gives "b", "o", "o" in turn; a Map of [["a", 1], ["b", 2], ["c", 3]] destructured gives the values 1, 2, 3; a Set of [1, 1, 2, 2, 3, 3] gives 1, 2, 3, with the duplicates already removed by the Set. One easily missed rule: the loop variable can use const, because each round creates a new variable — MDN states this explicitly. But reassigning that variable inside the body does not change the original value in the array: verified, adding one to each of [10, 20, 30] gives 11, 21, 31, while the original array stays [10, 20, 30]. On the cafe order page, for...of is handiest for adding up a total: prices is [12, 18, 25], and for (const price of prices) adds each price into total, giving 55 in the end, verified. The check for this step: when you hold a collection and need to do the same thing to each item, write for...of first; only switch to the for loop of the next step when you genuinely need the index.
Step 4: Choosing between for and for...of — use for only when you need the index
for...of is handy, but it has one shortcoming: it never tells you which round you are on. Some jobs cannot be done without that, like building a sentence where the last item needs "and" in front of it instead of a comma. MDN's cats example explains exactly this: first it uses for...of to append each name plus a comma after "My favorite big cats are ", giving "My favorite big cats are Leopard, Serval, Jaguar, Tiger, Caracal, Lion, " — with an extra comma after the last item, so the sentence is broken. Rewriting it as a for loop fixes it: for (let i = 0; i < cats.length; i++), checking i === cats.length - 1, appending "and Lion." for the last item and a name plus a comma otherwise. Verified: the result is "My favorite big cats are Leopard, Serval, Jaguar, Tiger, Caracal, and Lion.", and the sentence reads properly. MDN also points out the two most common mistakes when writing array loops with for: first, starting the index at 1 and forgetting that the first array index is 0, which skips the first item; second, writing the condition as i <= cats.length and forgetting that the last index is length - 1, which runs one round too many, so cats[6] is undefined — the array has six items and index 6 holds nothing. MDN's conclusion is blunt: if you do not need the index, for...of is the better choice — easier to read, with fewer chances to go wrong. On the cafe order page, the need for an index shows up most in "which table, which seat": a nested loop with tables 1 to 2 outside and seats 1 to 3 inside gives 6 combinations, from "Table 1, Seat 1" to "Table 2, Seat 3", verified. The check for this step: before writing a loop, ask whether you need to know which round this is. If not, use for...of; if yes, use for, and read the < versus <= in the condition once more.
Step 5: while — when you do not know how many rounds it will take
A for loop fits "you know how many times", but some jobs cannot be counted in advance: serving a queue depends on how many orders are left, a countdown depends on what number it has reached, reading data depends on when it runs out. That is when while fits: MDN writes the starting value first, then while (condition) with the code and the step inside. The three parts are the same as for, only placed differently: the starting value sits outside the loop, the step sits inside the loop body, and the condition still sits in the parentheses. MDN's countdown example is verified: let i = 10, while (i >= 0), checking inside whether i is 10 to write "Countdown 10", whether i is 0 to write "Blast off!", and otherwise writing the number itself, with i-- at the end of each round. The result is ["Countdown 10", 9, 8, 7, 6, 5, 4, 3, 2, 1, "Blast off!"], 11 lines in total, all verified. MDN also shows that while and for can be rewritten into each other: the cats sentence example written with while puts let i = 0 outside, while (i < cats.length) in the middle, the sentence building inside, and i++ at the end — the result is exactly the same. On the cafe order page, while fits "queues" best: queue is 3, while (queue > 0) serves one order per round and subtracts one from queue, giving the order 3, 2, 1, verified. There is one easy mistake here, but its consequence is the worst: forgetting the step leaves the condition true forever and the loop never stops. MDN warns explicitly that this is called an infinite loop, and the browser will either force it to stop or freeze. When writing while, write the step first, then the rest of the body — do not reverse that order. The check for this step: use for when you know how many rounds, while when you do not; when both work, pick the one whose three parts are easiest to see.
Step 6: do...while — it runs at least once
while has one characteristic: the condition is checked first, so if it is false from the start, the body never runs at all. do...while is the opposite: it runs the body first, then checks the condition, so no matter whether the condition starts true or false, it runs at least once. MDN writes the code and the step inside do, with while (condition) after it. The cats sentence example written with do...while gives exactly the same result as for and while. The difference only shows when the condition starts out false: verified, while (wi < 0) starting with wi = 0 runs zero times, a count of 0; the same start with do...while runs once before checking, a count of 1. On the cafe order page, do...while fits "do it once first, then ask whether to go on": serve one taster cup first, then ask whether the customer wants another; show a confirmation dialog once, then ask whether to continue. My judgment is that do...while rarely appears in beginner code — while is enough most of the time — but you should recognize it, so that reading someone else's do...while does not leave you staring: it is simply "run once first, then check", the while variant. The check for this step: before writing do...while, ask whether running once is acceptable when the condition starts out false. If not, do not use do...while, use while; if yes, use it, but leave a comment saying why at least one run is wanted.
Step 7: break — stop as soon as you find it
Sometimes a loop does not need to finish: once the contact you are looking for is found in the address book, stop; once the first sold-out drink is found on the menu, stop; running the remaining rounds is wasted work. MDN's tool for that is break: placed inside the loop body, it jumps out of the whole loop the moment it runs, and none of the later rounds happen. MDN's contacts example is verified: contacts holds "Chris:2232322", "Sarah:3453456", "Bill:7654322", "Mary:9998769", and "Dianne:9384975". To find Sarah, for...of compares them one by one, lowercasing the name first, and when it matches, writes "Sarah's number is 3453456." into the paragraph and breaks. Searching for "Nobody" matches nothing, the loop runs to the end, and the paragraph reads "Contact not found.". Case is not a worry either: the input is lowercased before comparing, so "sarah" finds Sarah just the same. break also appeared in switch, covered in step 9 of the conditionals guide — the same keyword, the same meaning: stop here. On the cafe order page, break fits "stop at the first match" best: the menu is latte in stock, mocha sold out, cappuccino in stock; for...of looks at them one by one, and the first one with stock 0 is mocha — found, break, verified. There is also a common companion pattern, "what if nothing is found": after the loop, check whether the result is still empty and show "not found". The contacts example does exactly that, checking after the loop whether the paragraph is empty. The check for this step: before writing a loop, ask whether finding one is enough. If yes, break must be written — do not let the loop run through the rest for nothing. If no, leave break out and let the loop finish.
Step 8: continue — skip this round only
break stops the whole loop; continue stops only this round, and the next round runs as normal. MDN puts it precisely: continue jumps to the next iteration of the loop. MDN's example finds integer squares: given a number, output every number from 1 to that number that is the square of an integer. The for loop runs from 1 to num, each round computing Math.sqrt(i) and comparing it with its Math.floor value; when the square root is not an integer, continue jumps straight to the next round without recording anything; only integers get written to the output. Verified: with num = 20 the result is [1, 4, 9, 16]; with num = 1 it is [1]. On the cafe order page, continue fits "skip the ones that do not qualify": the menu is latte in stock, mocha sold out, cappuccino in stock; for...of looks at each one, skips the zero-stock item with continue, and pushes the rest into the available list, giving ["latte", "cappuccino"], verified. break and continue are easy to confuse, so remember one line: break means "I am done playing, going home", continue means "I skip this round, back next round". One more detail: in a for loop, continue runs the step expression i++ first and then checks the condition; in a while loop, continue goes straight back to the condition check, so a step written after the continue is skipped — that is how a while loop with continue most easily forgets its step and becomes an infinite loop. My judgment is that beginners using continue inside while should be extra careful: put the step at the very top of the loop body, before any continue, even if it feels repetitive — better repetitive than skipped. The check for this step: after writing a loop with continue, run it once with a value that should definitely be skipped, confirm it really was skipped, and confirm the loop still stops.
Step 9: Do not mix up for...in and for...of — one gives keys, the other gives values
for...in and for...of look alike, but they mean completely different things, and the MDN for...of reference uses one example to draw the line. for...in iterates over the enumerable property names of an object, while for...of iterates over the values that an iterable object defines. For an array, for...in gives you indexes and extra property names, while for...of gives you the element values. Verified: on the array [3, 5, 7] with an extra foo property "hello" attached, for...in gives "0", "1", "2", "foo" in turn, while for...of gives 3, 5, 7. MDN's own example goes even further: it adds objCustom to Object.prototype and arrCustom to Array.prototype, and then for...in prints "arrCustom" and "objCustom" too. The body here uses the clean variant, with only its own foo property and no changes to prototypes; the difference between the two versions is noted in the evidence file. The conclusion is blunt: to get values out of an array, use for...of; to get indexes, use for; for...in is for iterating over an object's properties, not for iterating over arrays. On the cafe order page, this trap appears most when extra information is attached to a menu array: with a note property hanging off the array, for...in counts the note as another dish in the total, while for...of does not. The check for this step: when you see for...in, ask whether you want property names or values. If you want values, switch to for...of; only use for...in when you genuinely want to iterate over an object's properties, and remember it also prints inherited property names.
Step 10: Three traps when changing things inside a loop — indexes, length, and closures
A loop itself is not hard; changing things inside it is. The first trap is an out-of-range index, covered in step 4: i <= cats.length runs one round too many, and cats[6] is undefined, because the array has six items and index 6 holds nothing. The second trap is changing the array's length inside the loop: when the condition is i < arr.length but the body adds or removes items, length changes, so the number of rounds changes too, and things get messier the longer it runs. My judgment is that when a loop needs to change an array, first decide whether it is changing the array being iterated or a different one: changing a different one is fine, but changing the one being iterated should wait — record what needs changing, and apply it all after the loop finishes. The third trap is closures, which the MDN for reference explains at length: declaring the counter with let inside the for loop gives each round its own fresh variable, so a setTimeout callback printing i gives 0, 1, 2; switching to var, or declaring the counter outside the loop, makes all three callbacks print 3, 3, 3, because they share one variable, and by the time the callbacks run the loop has already finished with i at 3. Verified: with a 10-millisecond setTimeout, the let version gives [0, 1, 2] and the var version gives [3, 3, 3]. The full explanation of closures belongs to the closures guide; this guide only asks you to remember the conclusion: declare a for loop counter with let, never var, and never outside the loop. On the cafe order page, the three traps look like this: counting menu indexes from 1 and skipping the first dish; deleting a sold-out dish inside the total loop and shifting everything after it; and timed serving callbacks that all print the last table number. The check for this step: whenever a loop changes anything, stop and ask what exactly is being changed — the counter, the array length, or a variable outside the loop body. If it is none of the three, the change does nothing; if it is one of them, think through what this round and the next round will do before changing it.
Step 11: Nested loops — decide first which layer is outside
A loop inside another loop is completely legal; MDN's examples already nest conditions inside loops and loops inside conditions. The most common shape of a nested loop is "every kind paired with every kind": two tables, three seats each, six combinations in total. The outer loop runs the table numbers, the inner loop runs the seat numbers, and the outer loop only advances after the inner loop has completed a full round. Verified: tables 1 to 2 and seats 1 to 3 give 6 combinations, the first "Table 1, Seat 1" and the last "Table 2, Seat 3". Nested loops go wrong in the same place nested conditions do: once the layers multiply, it gets hard to tell which variable belongs to which layer. My judgment is that the rule for nested loops matches the rule for nested conditions: past two layers, stop and think about whether the inner layer should become its own function. One practical habit helps: stop calling the inner loop's variable i as well, and use j, or a more meaningful name — table for the table number, seat for the seat number — so anyone reading the code can see at a glance what each layer is doing. On the cafe order page, nested loops appear most as "each table orders several dishes": the outer layer is the table, the inner layer is that table's dishes, computing each table's total; or as daily sales statistics: the outer layer is the date, the inner layer is the time slot. The check for this step: after writing a nested loop, draw a small table on paper — the outer loop's rounds across the top, the inner loop's rounds down the side — check that the total number of cells is right and that the first and last cells are the ones you want, then write the code.
Step 12: Pre-launch checklist and a chart of what went wrong
The chart below shows the breakdown of 100 fictional loop mistakes in one month on the Greenstone Cafe order page. The numbers are invented examples, matched against the traps from the previous eleven steps: a wrong loop condition, running one round too few or too many, 22 times, the most; forgetting i++, so the loop never stops, 18 times; counting from 1, going out of range or skipping the first item, 15 times; using for...in on an array and treating the index as the value, 13 times; changing the array length inside the loop until it falls apart, 11 times; break in the wrong place, exiting too early or not at all, 9 times; mixing up continue and break, 7 times; using do...while as if it were while and running one extra round, 5 times. 22 + 18 + 15 + 13 + 11 + 9 + 7 + 5 = 100, and the books balance.
Before the order page's loop logic goes live, run through these seven questions. First, are the three parts clear? What is the start, when does it stop, how much does each round add — miss one, and the loop may run one round too many or never stop. Second, do you need the index? If not, use for...of; if yes, use for, and read the < versus <= in the condition once more. Third, is the step written? The step of while and do...while lives inside the loop body, and forgetting it means an infinite loop; continue skips it, so the step must come before any continue. Fourth, is break in the right place? Write break only when finding one is enough — in the wrong place it exits too early or never exits. Fifth, are continue and break straight? break stops the whole loop, continue skips only this round. Sixth, did the loop change anything? Changing the array length, the counter, or a variable outside the loop body — think through what this round and the next round will do before changing it. Seventh, is the nesting more than two layers deep? Past two layers, think about extracting the inner layer into a function, and give the variables meaningful names instead of reusing i. Once those seven questions are answered, go back to MDN's three docs: the Learn article covers the basic ideas and examples of loops, the for reference is the complete manual for the for statement, and the for...of reference is the rulebook for for...of. The three have different jobs, so do not go to the wrong door when checking a problem: for whether a particular form is allowed, read the matching reference; for how loops should be organized overall, go back to the Learn article. One last reminder: the full use of map, filter, and reduce lives in the array methods guide, and async loops and generators each have their own traps — read the matching MDN docs before writing from memory.
Comments (0)
Sources
Related articles
Every web page makes decisions all day: a total over 100 gets a discount, zero stock shows sold out. Following MDN's Making decisions in your code — conditionals, if...else, and switch: if and else if, comparison operators, truthy and falsy, logical operators, the classic || mistake, nested if and the dangling else, switch and fall-through, the ternary operator, and guard clauses.
localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.