SECTION 1
Historical Context & Motivation
Before programming languages existed, mathematicians and engineers already understood that many tasks require doing the same operation over and over. Calculating a table of logarithms, for example, meant applying the same formula hundreds of times with slightly different inputs. When the first computers were built in the 1940s, their creators realized that repetition was one of the most powerful capabilities a machine could offer—and the loop was born as the programming structure that makes repetition automatic.
1843 • Ada Lovelace's Algorithm
1949 • Assembly Language Jumps
1957 • FORTRAN's DO Loop
1972 • C Language Loops
1995 • JavaScript Arrives
The core question that loops answer is deceptively simple: how can we tell a computer to do something many times without writing the same code over and over? Understanding how to construct a loop—and how to predict exactly how many times it will run—is one of the most essential skills in programming.
SECTION 2
Core Principles & Definitions
Every loop in JavaScript—whether it is a for loop or a while loop—relies on a handful of foundational ideas. Once you understand these principles, you can read, write, and trace any loop you encounter.
Iteration
Loop Condition
true, the body runs. If false, the loop exits.Loop Variable (Counter)
i) tracks the current state of the loop. It is initialized, tested, and updated on every cycle.Update Step
i++) so the loop eventually reaches its exit condition. Without it, you get an infinite loop.Loop Body
{ } that executes on each iteration. This is where the real work happens.KEY TAKEAWAY
SECTION 3
Visual Explanation — The Loop Lifecycle
The diagram below shows the complete lifecycle of a for loop. Follow the arrows from initialization through the condition check, body execution, and update step. Notice how the flow cycles back to the condition after every update—this is what makes it a loop.
for loop from its initialization (purple) through the condition check (cyan diamond), body execution (green), and update step (amber). The arrow on the left shows the loop cycling back to the condition. When the condition becomes false, the loop exits to the right (red).A while loop follows the same diamond-body-update cycle, but the initialization and update are not built into the loop's header. You write them separately, which gives you more flexibility but also more responsibility. The key insight is that both loop types check the condition before entering the body. If the condition is already false at the start, the body never runs—not even once.
SECTION 4
How It Works — Syntax & Iteration Counting
The for Loop Syntax
A for loop packs three expressions into its parentheses, separated by semicolons. The first expression runs once before the loop begins. The second is the condition that is checked before each iteration. The third runs after each iteration.
FOR LOOP TEMPLATE
initialization — declares and sets the counter variable (runs once). condition — Boolean checked before each pass; loop exits when false. update — modifies the counter after each pass (e.g., i++). body — the statements that execute on each iteration.
The while Loop Syntax
A while loop only has a condition in its header. You must handle initialization before the loop and the update inside the body. This makes while loops ideal when you don't know in advance how many iterations you need.
WHILE LOOP TEMPLATE
The initialization must appear before the while statement. The update must be inside the body, or the loop will never terminate.
Counting Iterations
For a standard counting loop that starts at start, ends before end, and increments by step, you can predict the number of iterations with a simple formula.
ITERATION COUNT FORMULA
The ceiling function ⌈ ⌉ rounds up to the nearest whole number. For for (let i = 0; i < 10; i += 2): iterations = ⌈(10 − 0) / 2⌉ = 5. The loop variable takes on values 0, 2, 4, 6, 8.
SECTION 5
Tracing Loops Step by Step
Tracing a loop means tracking the value of every variable through each iteration. This is the single most reliable way to understand what a loop does and to debug it when something goes wrong. The table and diagram below walk you through a complete trace of a for loop and a while loop.
Trace Table: for (let i = 1; i <= 4; i++)
| Check # | i value | Condition (i <= 4) | Body Runs? | i after update |
|---|---|---|---|---|
| 1 | 1 | true | ✅ Yes (prints 1) | 2 |
| 2 | 2 | true | ✅ Yes (prints 2) | 3 |
| 3 | 3 | true | ✅ Yes (prints 3) | 4 |
| 4 | 4 | true | ✅ Yes (prints 4) | 5 |
| 5 | 5 | false | ❌ No — EXIT | — |
Trace of for (let i = 1; i <= 4; i++) { console.log(i); }
while loop where x starts at 16 and is halved each iteration. The loop runs 5 times because 16 → 8 → 4 → 2 → 1 → 0.5, and 0.5 fails the condition x >= 1.Pro Tip: Off-By-One Errors
< and <=. For example, i < 5 gives 5 iterations (0–4), but i <= 5 gives 6 iterations (0–5). When in doubt, build a trace table!SECTION 6
Worked Example — Summing Numbers with a Loop
Let's work through a complete problem: write a for loop that calculates the sum of all integers from 1 to 10, then convert it to an equivalent while loop. We will trace both to confirm they produce the same result.
Sum of 1 to 10 (for loop)
- 1
Step 1 — Identify the Goal
We need to add 1 + 2 + 3 + ... + 10 and store the result. We'll use a variable calledsumto accumulate the total, starting at 0. - 2
Step 2 — Write the for Loop
We initializeiat 1 and loop whilei <= 10. On each iteration, we additosum:let sum = 0; for (let i = 1; i <= 10; i++) { sum += i; } - 3
Step 3 — Count Iterations
Using our formula: iterations = (end − start) / step + 1 = (10 − 1) / 1 + 1 = 10. The+1accounts for the inclusive upper bound (<=instead of<).10 iterations - 4
Step 4 — Trace Key Values
After iteration 1: sum = 1. After iteration 2: sum = 3. After iteration 3: sum = 6. ... After iteration 10: sum = 55. We can verify: 10 × 11 / 2 = 55. ✅sum = 55 - 5
Step 5 — Convert to while Loop
Move initialization before the loop and update into the body:let sum = 0; let i = 1; while (i <= 10) { sum += i; i++; }. This produces the same result (55) in the same number of iterations. The only difference is where the three parts live in the code.Both loops → sum = 55
SECTION 7
for vs. while — When to Use Each
Both for and while loops can do exactly the same things—they are interchangeable in terms of power. However, each has situations where it feels more natural and leads to cleaner, more readable code.
| Feature | for loop | while loop |
|---|---|---|
| Best when... | You know how many iterations you need in advance. | You don't know how many iterations; you loop until a condition changes. |
| Init, condition, update | All three are in the loop header—compact and easy to scan. | Spread across multiple lines—more flexible but easier to forget the update. |
| Common use case | Iterating through arrays, counting from A to B, repeating N times. | Reading user input until valid, game loops, waiting for a condition. |
| Infinite loop risk | Low—update is built into the header, harder to forget. | Higher—if you forget the update inside the body, the loop never ends. |
| Example | for (let i = 0; i < arr.length; i++) | while (guess !== secret) |
Comparison of for and while loops in JavaScript
KEY TAKEAWAY
SECTION 8
Connection to Advanced Concepts
The for and while loops you've learned are the foundation for many advanced programming patterns. As you grow as a programmer, you'll encounter loop variations and related concepts that build directly on these fundamentals.
| What You Know Now | What Comes Next | Why It Matters |
|---|---|---|
for (let i = 0; i < arr.length; i++) | for...of and forEach() | Cleaner syntax for iterating over arrays without managing an index variable. |
| Single loops | Nested loops | Loops inside loops let you work with 2D data like grids, tables, and game boards. |
while (condition) | do...while | Guarantees the body runs at least once, checking the condition after the first pass. |
| Loops with counters | Recursion | A function that calls itself replaces the loop entirely—same idea of repetition, different structure. |
How basic loops connect to advanced patterns
Every one of these advanced tools relies on the same core logic: initialize, check a condition, do work, update, repeat. If you understand that cycle thoroughly—which is exactly what tracing teaches you—you will find that nested loops, higher-order array methods, and even recursion are natural extensions of what you already know.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
while loop might run zero times. Under what circumstances would the loop body never execute?Show answer
while loop checks its condition before the first iteration. If that condition is already false when the loop is first reached, the body is skipped entirely, resulting in zero iterations. For example, let x = 0; while (x > 10) { console.log(x); } never prints anything because 0 > 10 is false from the start. This is called a "pre-test" loop—the test happens before any work is done.Question 2: BASIC CALCULATION
count? let count = 0; for (let i = 2; i < 12; i += 3) { count++; }Show answer
i takes the values 2, 5, 8, 11. When i becomes 14 after the fourth iteration, the condition i < 12 is false, so the loop exits. The body ran 4 times, incrementing count each time. Using the formula: ⌈(12 − 2) / 3⌉ = ⌈10/3⌉ = ⌈3.33⌉ = 4. Therefore, count equals 4.Question 3: INTERMEDIATE
for loop as an equivalent while loop, then trace both to confirm they produce the same output: for (let n = 10; n >= 1; n -= 2) { console.log(n); }Show answer
let n = 10; while (n >= 1) { console.log(n); n -= 2; }. Tracing both: n takes values 10, 8, 6, 4, 2. After printing 2, n becomes 0, which fails n >= 1. Both loops output: 10, 8, 6, 4, 2 (5 iterations). The key conversion steps are: move initialization before the while, move the update to the end of the body, and keep the condition identical.Question 4: APPLIED
while loop (using pseudocode for prompt()) that implements this logic. How many iterations could this loop have at minimum and maximum?Show answer
let attempts = 0; let guess = ''; while (guess !== 'open123' && attempts < 3) { guess = prompt('Enter password:'); attempts++; }. The minimum number of iterations is 1—if the student types the correct password on the first try. The maximum is 3—if the student gets it wrong three times, attempts < 3 becomes false and the loop exits. This loop uses a compound condition with &&, which means both conditions must be true to continue looping. Either a correct password or exhausting attempts will end the loop.Question 5: CRITICAL THINKING
let x = 1; while (x !== 10) { x += 3; }. Will this loop ever terminate? Trace the values of x to explain your answer. Then propose a one-character fix to the condition that would make the loop safely terminate.Show answer
x starts at 1, then becomes 4, 7, 10, 13, 16... Wait—x actually does hit 10 (1 → 4 → 7 → 10), so the condition x !== 10 becomes false and the loop terminates after 3 iterations. But this is fragile—if the starting value or step changed (e.g., x += 4), x would jump from 9 to 13, skipping 10 entirely, creating an infinite loop. A safer fix: change !== to < (i.e., x < 10). This way, any value ≥ 10 exits the loop, making it robust against different step sizes.SUMMARY
Lesson Summary
Summary
Loops are programming's way of saying "repeat this." A for loop bundles its initialization, condition, and update into a single header line, making it ideal when you know in advance how many iterations you need. A while loop separates these parts, giving you more flexibility for situations where the number of repetitions depends on runtime conditions—like user input or data processing.
To predict or verify a loop's behavior, build a trace table that tracks the loop variable through each pass: check the condition, execute the body, apply the update, and repeat. Watch out for off-by-one errors (confusing < with <=) and infinite loops (forgetting the update step). These two loop types form the backbone of every program that processes lists, accumulates totals, validates input, or animates graphics.