COMPUTER PROGRAMMING 1 (JAVASCRIPT) • CONDITIONALS, LOOPS & COMMON PATTERNS

For & While Loops — I can write for and while loops and trace how many iterations run and why at my level.

Master repetition in code by understanding how loops iterate, when they stop, and which type to choose.

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
Ada Lovelace wrote the first published algorithm for Charles Babbage's Analytical Engine. Her notes described a loop that would repeat a sequence of operations, making her the first person to formally describe iterative computation.
1949
Assembly Language Jumps
Early assembly languages used JUMP instructions to send the processor back to an earlier line of code. This raw mechanism is the ancestor of every loop you write today, but it was error-prone and hard to read.
1957
FORTRAN's DO Loop
FORTRAN, one of the first high-level languages, introduced the DO loop—a structured way to repeat code a known number of times. This concept directly influenced the modern for loop.
1972
C Language Loops
The C programming language formalized the for loop with three parts (initialization, condition, update) and the while loop with a single condition. JavaScript adopted this exact syntax in 1995.
1995
JavaScript Arrives
Brendan Eich created JavaScript in just 10 days. He borrowed loop syntax from C and Java, giving web developers the for and while loops you will learn in this lesson.

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.

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.

1

Iteration

One single pass through the body of a loop is called an iteration. If a loop's body runs 5 times, we say the loop performs 5 iterations.
2

Loop Condition

Before each iteration, the computer checks a condition (a Boolean expression). If it evaluates to true, the body runs. If false, the loop exits.
3

Loop Variable (Counter)

A loop variable (often called i) tracks the current state of the loop. It is initialized, tested, and updated on every cycle.
4

Update Step

The update step changes the loop variable (e.g., i++) so the loop eventually reaches its exit condition. Without it, you get an infinite loop.
5

Loop Body

The loop body is the block of code inside the curly braces { } that executes on each iteration. This is where the real work happens.
✦ KEY TAKEAWAY
Think of a loop like running laps around a track. The condition is the coach saying "keep running until you've done 10 laps." The loop variable is your lap counter. The update step is you adding one to your count each time you cross the start line. If you forget to count (no update), you run forever—that is an infinite loop.

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.

The flowchart traces a 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.

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
for (initialization; condition; update) { body }
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
while (condition) { body; update; }
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
iterations = ⌈(end − start) / step⌉
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.

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++)

Trace of for (let i = 1; i <= 4; i++) { console.log(i); }
Check #i valueCondition (i <= 4)Body Runs?i after update
11true✅ Yes (prints 1)2
22true✅ Yes (prints 2)3
33true✅ Yes (prints 3)4
44true✅ Yes (prints 4)5
55false❌ No — EXIT—
This trace table shows a 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
The most common loop bug is being off by one iteration. This usually happens because of confusion between < 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!

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 GoalWe need to add 1 + 2 + 3 + ... + 10 and store the result. We'll use a variable called sum to accumulate the total, starting at 0.
2
Step 2 — Write the for LoopWe initialize i at 1 and loop while i <= 10. On each iteration, we add i to sum: let sum = 0; for (let i = 1; i <= 10; i++) { sum += i; }
3
Step 3 — Count IterationsUsing our formula: iterations = (end − start) / step + 1 = (10 − 1) / 1 + 1 = 10. The +1 accounts for the inclusive upper bound (<= instead of <).
10 iterations
4
Step 4 — Trace Key ValuesAfter 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 LoopMove 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

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.

Comparison of for and while loops in JavaScript
Featurefor loopwhile 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, updateAll 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 caseIterating through arrays, counting from A to B, repeating N times.Reading user input until valid, game loops, waiting for a condition.
Infinite loop riskLow—update is built into the header, harder to forget.Higher—if you forget the update inside the body, the loop never ends.
Examplefor (let i = 0; i < arr.length; i++)while (guess !== secret)
✦ KEY TAKEAWAY
Think of a for loop as a GPS with a known destination—you set the start, end, and step size before you begin driving. A while loop is more like driving until you see a gas station—you don't know exactly when you'll stop, but you know the condition that will make you pull over.

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.

How basic loops connect to advanced patterns
What You Know NowWhat Comes NextWhy 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 loopsNested loopsLoops inside loops let you work with 2D data like grids, tables, and game boards.
while (condition)do...whileGuarantees the body runs at least once, checking the condition after the first pass.
Loops with countersRecursionA function that calls itself replaces the loop entirely—same idea of repetition, different structure.

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words why a while loop might run zero times. Under what circumstances would the loop body never execute?
PROBLEM 2 — BASIC CALCULATION
How many times does the following loop iterate, and what is the final value of count? let count = 0; for (let i = 2; i < 12; i += 3) { count++; }
PROBLEM 3 — INTERMEDIATE
Rewrite the following 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); }
PROBLEM 4 — APPLIED
A teacher wants a program that asks a student to enter a password. The program should keep asking until the student types "open123" or has made 3 incorrect attempts. Write a while loop (using pseudocode for prompt()) that implements this logic. How many iterations could this loop have at minimum and maximum?
PROBLEM 5 — CRITICAL THINKING
Consider this loop: 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.

Lesson 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.

Varsity Tutors • Computer Programming 1 (JavaScript) • For & While Loops