Suggest an editImprove this articleRefine the answer for “What is a pre-condition loop?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **pre-condition loop** is a loop that first checks a logical condition before every iteration, and only executes the loop body if it is true. The classic example is the while statement; if the condition is false from the start, the loop body never runs. - The condition is checked before the body runs. - The number of iterations is not known in advance. - Typical examples: while, for with a condition in the header. **Key point:** it is flexible when the number of repetitions depends on data at runtime, but termination is only guaranteed if the condition sooner or later becomes false.Shown above the full answer for quick recall.Answer (EN)Image## What is a pre-condition loop? ### Short answer A pre-condition loop is a loop that first checks a logical condition before every iteration, and only executes the loop body if it is true. The classic example is the while statement; if the condition is false from the start, the loop body never runs. - The condition is checked before the body runs. - The number of iterations is not known in advance. - Typical examples: while, for with a condition in the header. ### Detailed breakdown #### Definition and general idea A pre-condition loop is organized so that entering the loop body is only possible while the condition is true. At every step the condition is re-evaluated, which lets the loop stop as soon as the goal is reached (or the data runs out). #### Basic syntax (using JavaScript as an example) ``` while (condition) { // loop body // change data/counters so that condition eventually becomes false } ``` #### Key properties - The body may never run (if the condition is false immediately). - Termination is guaranteed if the condition sooner or later becomes false. - Flexible when the number of repetitions depends on data at runtime. #### Order of execution 1. Evaluate condition. 2. If condition is true, execute the body. 3. Repeat from step 1. #### Code examples ##### JS: finding the first negative number in an array ``` const arr = [3, 5, 8, 0, -2, 10]; let i = 0; let firstNegative = null; while (i < arr.length && firstNegative === null) { if (arr[i] < 0) { firstNegative = arr[i]; } else { i += 1; // it is important to update the counter, otherwise the loop is infinite } } console.log(firstNegative); // -2 ``` ##### JS (non-blocking): waiting for a condition with a timeout In browser/Node.js code, you cannot spin an "empty" while to wait - it blocks the thread. Use await inside the loop instead: ``` async function waitFor(predicate, timeoutMs = 2000, intervalMs = 50) { const end = Date.now() + timeoutMs; while (!predicate()) { // the precondition is checked before every iteration if (Date.now() > end) throw new Error('Timeout'); await new Promise(r => setTimeout(r, intervalMs)); } } // Usage example: wait until an element appears on the page // await waitFor(() => !!document.querySelector('#app-ready')); ``` #### The difference from a post-condition loop (do...while) A post-condition loop checks the condition after the body runs, so the body executes at least once. ``` // Pre-condition (while): the body may never run let n = 0; while (n > 0) { console.log('Will not print'); } // Post-condition (do...while): the body runs at least once let m = 0; do { console.log('Runs once'); } while (m > 0); ``` #### Typical mistakes and how to avoid them - An infinite loop: forgetting to change the variables that affect the condition. Solution: update counters/state inside the loop body, or use for where appropriate. - Comparing floating-point numbers for equality. Solution: check via a range (|a-b| < eps), or use >/< comparisons. - Mutating a collection while iterating over it (changing an array's length during iteration). Solution: iterate over a copy, or control the index and bounds. - Blocking the UI/server in JS with a long synchronous while. Solution: split the work into chunks (setTimeout/queueMicrotask), or use await inside the loop. - A condition that is too complex and hard to maintain. Solution: move the check into a function with a descriptive name (isReady(), hasMore()). #### Invariant and termination (for interviews) An invariant is a property that is true before and after every iteration. For loop correctness, formulate: - The invariant: what does not change (for example, "all processed elements satisfy the condition"). - A measure of progress: what monotonically approaches completion (an index grows, a queue shrinks, time runs out). - The exit condition: when and why it will become false. #### When to use it - The number of repetitions is not known in advance and depends on data/events. - The condition needs to be checked before performing a step (for example, whether there is more data). - Reading from a stream/queue until it is empty, searching until a result is found, waiting for a state. ### Summary A pre-condition loop (for example, while) checks the condition before entering the body, so the body runs only if the condition is true. It is a convenient tool for problems with an unknown number of iterations in advance; it is important to ensure that the state changes in a way that leads to the condition becoming false, to avoid infinite loops.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.