Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

JavaScript Loops: Why We Use Them and the First Three Types

JavaScript loops repeat instructions without duplicated code. Learn how for, while and do...while work, when each condition is checked, and how to avoid infinite loops.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JavaScript loops repeat a block of code so you can handle similar work across multiple steps or items without writing a separate copy of the instructions for every pass. The three basic forms are for, while and do...while: they differ in where they put the setup and update, and when they check whether to continue.

Why use loops in JavaScript?

Use a loop when the same kind of action needs to happen repeatedly—for example, drawing many circles or processing a list of items. Instead of duplicating the code for each pass, write the instructions once and let the loop repeat them.

As an Amazon Associate I earn from qualifying purchases.

A loop continues while its condition says another pass should happen. For every loop, make sure something changes so that the condition can eventually become false; otherwise, the loop may run indefinitely.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How does a for loop work?

A for loop keeps its initialization, condition and afterthought together in this form:

for (initialization; condition; afterthought) {
  // repeated instructions
}

It is a clear choice when you know the counter and stopping rule together. In this example, the loop logs the numbers 0 through 4:

for (let i = 0; i < 5; i++) {
  console.log(i);
}
  1. let i = 0 runs once before the first pass and initializes the counter.
  2. i < 5 is checked before each pass. If it is true, the body runs; if it is false, the loop ends.
  3. i++ runs after each pass, increasing the counter before the next condition check.

Because the condition is checked before the body, a for loop can run zero times if its condition starts false.

When should you use a while loop?

Use while when you want to repeat work as long as a condition remains true, especially when the stopping point is not simply a fixed count. It checks before each pass:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
let attempts = 0;
while (attempts < 3) {
  attempts++;
}

Here, the body runs while attempts is less than 3. The increment changes the value on each pass, allowing the condition to become false. Since the test happens first, the body may run zero times if the condition is false from the outset.

When is do...while a better fit?

Choose do...while when an action needs to happen once before you decide whether it should repeat. It tests the condition after the body, so the body always runs at least once. A common pattern is to request input and then check whether it is valid:

let input;
do {
  input = getInput();
} while (!isValid(input));

getInput and isValid represent functions supplied by the application. The loop asks for input before checking whether another pass is needed.

How do the three loop forms differ?

Form When the condition is checked Can the body run zero times? Introductory use
for Before each pass Yes Known counter or range; setup, test and update stay together.
while Before each pass Yes Repeat while a condition remains true.
do...while After each pass No Perform an action once, then decide whether to repeat.

Are these all the JavaScript loop types?

No. for, while and do...while are three basic control-flow forms, not the whole iteration toolkit. JavaScript also has for...of for iterable values such as array items, and for...in for enumerable object properties. When you want to process collection values and do not need their indexes, MDN recommends considering for...of.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How can you avoid an infinite loop?

  • Check that the condition can eventually become false.
  • Make sure each pass updates a counter or otherwise changes the state used by the condition.
  • For a while loop, do not forget to update that state inside the body when needed.
  • For a do...while loop, remember that the body runs once even if the condition would initially be false.

MDN’s guides explain loop structure and iteration in more detail: Loops and iteration and Loops and iteration in the JavaScript Guide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.