Lesson 4: Loops and Iteration

“Learn how to automate repetitive tasks by writing loop structures.”

Lesson 4: Loops and Iteration

Why Do We Need Loops?

Imagine needing to print numbers from 1 to 1000, or send transactional emails to 10,000 customers. Writing these operations line-by-line is impossible. A [loop] is a programming concept that executes a block of code repeatedly as long as a specified condition remains true.

---

The Standard 'For' Loop

The most commonly used loop structure is the for loop. It bundles state initialization, termination condition, and increment expression together.

for (initialization; condition; update) {
// code block to repeat
}

#### Code Example: Basic Count
for (let i = 1; i <= 5; i++) {
console.log("Iteration number:", i);
}

#### Visual Output Demonstration:
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5

---

The 'While' Loop

Use a while loop when you do not know the exact number of iterations beforehand, but know the condition that must be met to stop execution.

#### Code Example: Simulating a Dice Roll
let rollResult = 0;
let rollCount = 0;

while (rollResult !== 6) {
rollResult = Math.floor(Math.random() * 6) + 1;
rollCount++;
console.log(Roll ${rollCount}: Player rolled a ${rollResult});
}

#### Visual Output Demonstration:
Roll 1: Player rolled a 3
Roll 2: Player rolled a 1
Roll 3: Player rolled a 6

*(Note: Your output will differ due to the random nature of calculations)*.

For standard references on random functions, check MDN Math Reference.

---

Controlling Loops: break and continue

We can modify loop flow dynamically using control signals:
* break: Exits the loop entirely, halting execution.
* continue: Skips the current iteration and jumps directly to the next cycle.

#### Code Example: Filtering with Continue
for (let i = 1; i <= 6; i++) {
if (i === 3) {
console.log("Skipping loop element 3.");
continue;
}
if (i === 5) {
console.log("Breaking out at 5.");
break;
}
console.log("Processing index:", i);
}

#### Visual Output Demonstration:
Processing index: 1
Processing index: 2
Skipping loop element 3.
Processing index: 4
Breaking out at 5.

---

Frequently Asked Questions (FAQs)

#### Q1: What causes an 'infinite loop', and how do I stop it?
* An infinite loop occurs when the termination condition never becomes false (e.g., while (true)). It can crash your web browser or slow down your system. To stop it, close your running browser tab or stop the terminal execution.

#### Q2: What is the difference between 'while' and 'do-while' loops?
* A while loop checks the condition *before* executing the code block. A do-while loop executes the block *once* first, then checks the condition to decide whether to repeat, guaranteeing that the block runs at least once.

#### Q3: When should I choose 'for' over 'while'?
* Use a for loop when you know exactly how many times the loop should run (e.g., iterating a specific number of times). Use a while loop when the number of cycles depends on external factors (like user input or random results).

Shanawar AliFounder and developer at S Pro Coder, sharing practical coding and technology guides.