Loops in JavaScript

JavaScript offers several loop constructs to repeat work over ranges, conditions, and collections. The following types of loops are commonly used:

Types of Loops

Condition-controlled loops (entry and exit control)

These loops depend on a boolean condition (true or false). You often do not know in advance how many times they will run.

While loop

The while loop evaluates its condition before each iteration and may run zero times if the condition is initially false. It suits open-ended repetition where the termination is driven by a runtime condition rather than an index. To avoid infinite loops, ensure the loop body progresses state so that the condition eventually becomes false, and apply break or continue as needed for control flow.

Do...while loop

The do...while loop executes the body once before evaluating the condition, which makes it a post-test construct. Because the check happens after the first pass, the loop always runs at least once and then continues while the condition remains true. This pattern is well suited to input validation or repeat-until workflows, and it supports the usual break and continue controls for precise flow management.

Counter-controlled loops (deterministic)

Use this group when the number of iterations is known or controlled by an index.

For loop

The for loop is a classic counter-controlled construct that initializes a variable, checks a condition before each iteration, and updates the counter at the end. It is ideal when you know the number of iterations in advance or need access to the index for calculations or lookups. As with other loops, you can use break to exit early and continue to skip to the next pass, and labels allow targeting outer loops when nested.

Collection-controlled loops (iterators)

These modern loops are specialized for traversing data structures (arrays, objects, sets) without manually managing a counter.

for...in loop

The for...in statement iterates over the enumerable property keys of an object, including inherited ones unless you explicitly filter them out. Because key order is not guaranteed, it is not appropriate for array iteration when you rely on index order. When working with plain objects, pair it with Object.hasOwn or Object.prototype.hasOwnProperty to restrict iteration to own properties and avoid surprises from the prototype chain.

Use this loop to iterate over the enumerable properties of an object. For arrays, it would yield the indexes (0, 1, 2, …), so it is generally avoided there.

const user = { name: "Jerry", ID: 42 };
for (const key in user) {
    console.log(key); // "name", "ID"
}

for...of loop

The for...of loop iterates over values produced by any iterable, such as arrays, strings, Maps, Sets, and generator results. It preserves the iterable's natural order and yields elements directly rather than numeric indexes, which makes code more readable. In asynchronous code, for await...of lets you consume async iterables in sequence while awaiting each item.

Diese Schleife ist der modernste Weg, um über iterierbare Datentypen (Arrays, Strings, Maps, Sets) zu gehen. Sie liefert dir direkt den Inhalt der Elemente.

  • Fokus: Der Wert des Elements.

  • Vorteil: Sehr lesbar; unterstützt break, continue und await.

  • Beispiel:

    JavaScript
    
    const koffer = ["Hemd", "Hose"];
    for (const item of koffer) {
        console.log(item); // "Hemd", "Hose"
    }
    

ForEach Schleife

Eigentlich eine Array-Methode, die für jedes Element eine bereitgestellte Funktion ausführt. Sie ist der "Go-to"-Standard für einfache Operationen auf Listen.

  • Fokus: Das Element (und optional der Index) innerhalb eines Funktionsaufrufs.

  • Besonderheit: Kann nicht mit break oder continue vorzeitig abgebrochen werden.

  • Beispiel:

    JavaScript
    
    const zahlen = [10, 20];
    zahlen.forEach((wert, index) => {
        console.log(`Pos ${index}: ${wert}`);
    

Labeled statements

A labeled statement prefixes a statement or loop with an identifier followed by a colon, which creates a named target for control flow. In nested scenarios, labels enable break and continue to act on an outer loop rather than only the nearest one. Because labels can obscure the flow when overused, apply them sparingly and prefer clear loop structure first.

Break and Continue

The break statement terminates the nearest enclosing loop or switch immediately, transferring control to the statement that follows it. By contrast, continue skips the remainder of the current iteration and proceeds with the next cycle of the loop. When combined with labels, both statements can target specific outer loops, but use this power sparingly to keep control flow readable.

📗

Related Pages:

  • Enter page link

📘

Related Documentation:

  • Enter context key link