JavaScript Loop Invariants and Termination Reasoning
Quick answer
A loop invariant is a claim that holds at a chosen point before and after each iteration. It helps establish correctness; a separate progress argument establishes termination.
How it works
For a sum loop with counter i, choose the loop-head invariant: sum equals the sum of integers 1 through i-1. It holds initially (i=1, sum=0); adding i and incrementing i preserves it. At exit for nonnegative integer n, i=n+1 and sum is the requested total. The remaining iteration count decreases each step. Use bounded safe integers so arithmetic and progress match the mathematical argument.
const n = 4;let sum = 0;let i = 1;while (i <= n) { console.log(i, sum); sum += i; i++; }console.log(i, sum);Expected output in Node.js:
1 02 13 34 65 10At each logged loop head, sum covers precisely the preceding integers.
let left = 9;let removed = 0;while (left > 0) { left--; removed++; }console.log(left, removed, left + removed);Expected output in Node.js:
0 9 9The invariant left + removed = 9 is preserved, and left decreases to zero.
Common mistakes
An invariant alone does not prove a loop stops. A counter may fail to change, or numeric precision may invalidate an unbounded integer argument. State the allowed input range.
Practice
Write the invariant and a decreasing progress measure for each example; trace n=0 separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Loop Invariants and Termination Reasoning — Knowledge Check
Apply the taught concept and reason about the result.
What is a loop invariant?
At loop head with i=3 and sum covering integers 1 through i-1, what is sum?
Does an invariant alone prove termination?
For left-- and removed++ starting at 9 and 0, which expression stays constant?
Why restrict a counting proof to appropriate safe integers?