Loops and Iteration
Learn how to repeat actions efficiently using loops to process collections and automate repetitive tasks.
Why Use Loops?
// Without loops (tedious):console.log(1);console.log(2);console.log(3);// ... up to 10// With loops (efficient):for (let i = 1; i <= 10; i++) {console.log(i);}
1
2
3
...
10Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.
For Loop
// Count from 0 to 4for (let i = 0; i < 5; i++) {console.log("Count: " + i);}// Countdown from 5 to 1for (let count = 5; count > 0; count--) {console.log(count);}
Count: 0
Count: 1
...
5
4
3
2
1Structure: for (initialization; condition; increment)
While Loop
// While condition is truelet counter = 3;while (counter > 0) {console.log(counter);counter--;}// Password validation examplelet password = "";while (password !== "secret123") {password = prompt("Enter password:");}
3
2
1
(Password prompt until correct)Use when you don't know how many iterations are needed beforehand.
Do-While Loop
// Runs at least oncelet userInput;do {userInput = prompt("Enter yes or no:");} while (userInput !== "yes" && userInput !== "no");
Keeps prompting until valid inputUse when you need to execute the loop body at least once before checking condition.
Looping Through Arrays
// Traditional for loopconst fruits = ["apple", "banana", "orange"];for (let i = 0; i < fruits.length; i++) {console.log(fruits[i]);}// Modern for...of loopfor (const fruit of fruits) {console.log(fruit.toUpperCase());}
apple
banana
orange
APPLE
BANANA
ORANGEfor...of is cleaner for array iteration when index isn't needed.
Break and Continue
// Break: Exit loop earlyfor (let i = 1; i <= 10; i++) {if (i === 6) break;console.log(i);}// Continue: Skip current iterationfor (let i = 1; i <= 5; i++) {if (i === 3) continue;console.log(i);}
1
2
3
4
5
---
1
2
4
5break exits the loop completely, continue skips to next iteration.
Nested Loops
// Multiplication tablefor (let i = 1; i <= 3; i++) {for (let j = 1; j <= 3; j++) {console.log(`${i} * ${j} = ${i * j}`);}}
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
...
3 * 3 = 9Use nested loops for multi-dimensional data structures or combinatorial operations.
Common Loop Mistakes
// 1. Infinite loopswhile (true) { /* ❌ Runs forever */ }for (let i=0; i<10; i--) { /* ❌ Never ends */ }// 2. Off-by-one errorsfor (let i=0; i <= 5; i++) { /* Runs 6 times */ }// 3. Modifying array while loopingconst numbers = [1,2,3];for (let i=0; i<numbers.length; i++) {numbers.pop(); // ❌ Causes unexpected behavior}// 4. Using var in loopsfor (var i=0; i<5; i++) { /* i leaks out */ }console.log(i); // 5 (should use let)
Always test edge cases and consider loop termination conditions carefully.
Practical Loop Examples
// 1. Sum array elementsconst prices = [4.99, 12.50, 3.75];let total = 0;for (const price of prices) {total += price;}// 2. Find maximum valueconst scores = [88, 92, 78, 95];let max = scores[0];for (let i = 1; i < scores.length; i++) {if (scores[i] > max) max = scores[i];}// 3. Filter arrayconst numbers = [1,2,3,4,5,6];const evens = [];for (const num of numbers) {if (num % 2 === 0) evens.push(num);}
total: 21.24
max: 95
evens: [2,4,6]Interactive Loops
// For loop buttondocument.getElementById("forLoopBtn").addEventListener("click", () => {let output = "";for (let i = 1; i <= 5; i++) {output += `Iteration ${i}\n`;}document.getElementById("output").textContent = output;});// Array processing buttondocument.getElementById("arrayBtn").addEventListener("click", () => {const products = ["Laptop", "Phone", "Tablet"];let html = "<ul>";for (const product of products) {html += `<li>${product}</li>`;}html += "</ul>";document.getElementById("output").innerHTML = html;});
Your Task: Number Analyzer
Create JavaScript code that:
- Adds click handlers for all four buttons
- For each button:
- For Loop: Generate and display multiplication table (1-5)
- While Loop: Generate random numbers (1-100) until one > 90, display all attempts
- Process Array:
Display: sum, average, min, maxconst numbers = [7, 23, 14, 42, 8, 51]; - Nested Loops:Create a 4x4 grid of asterisks using nested loops:
* * * *
* * * *
* * * *
* * * *
- Use appropriate loop types for each task
- Include at least:
- One break/continue statement
- One for...of loop
- One nested loop
Challenge: For the array processing, also find and display prime numbers
Tip: For min/max, initialize with first array element
Why Use Loops?
Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.
Loops and Iteration
Learn how to repeat actions efficiently using loops to process collections and automate repetitive tasks.
Why Use Loops?
// Without loops (tedious):console.log(1);console.log(2);console.log(3);// ... up to 10// With loops (efficient):for (let i = 1; i <= 10; i++) {console.log(i);}
1
2
3
...
10Loops automate repetitive tasks, making code shorter, more readable, and easier to maintain.
For Loop
// Count from 0 to 4for (let i = 0; i < 5; i++) {console.log("Count: " + i);}// Countdown from 5 to 1for (let count = 5; count > 0; count--) {console.log(count);}
Count: 0
Count: 1
...
5
4
3
2
1Structure: for (initialization; condition; increment)
While Loop
// While condition is truelet counter = 3;while (counter > 0) {console.log(counter);counter--;}// Password validation examplelet password = "";while (password !== "secret123") {password = prompt("Enter password:");}
3
2
1
(Password prompt until correct)Use when you don't know how many iterations are needed beforehand.
Do-While Loop
// Runs at least oncelet userInput;do {userInput = prompt("Enter yes or no:");} while (userInput !== "yes" && userInput !== "no");
Keeps prompting until valid inputUse when you need to execute the loop body at least once before checking condition.
Looping Through Arrays
// Traditional for loopconst fruits = ["apple", "banana", "orange"];for (let i = 0; i < fruits.length; i++) {console.log(fruits[i]);}// Modern for...of loopfor (const fruit of fruits) {console.log(fruit.toUpperCase());}
apple
banana
orange
APPLE
BANANA
ORANGEfor...of is cleaner for array iteration when index isn't needed.
Break and Continue
// Break: Exit loop earlyfor (let i = 1; i <= 10; i++) {if (i === 6) break;console.log(i);}// Continue: Skip current iterationfor (let i = 1; i <= 5; i++) {if (i === 3) continue;console.log(i);}
1
2
3
4
5
---
1
2
4
5break exits the loop completely, continue skips to next iteration.
Nested Loops
// Multiplication tablefor (let i = 1; i <= 3; i++) {for (let j = 1; j <= 3; j++) {console.log(`${i} * ${j} = ${i * j}`);}}
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
...
3 * 3 = 9Use nested loops for multi-dimensional data structures or combinatorial operations.
Common Loop Mistakes
// 1. Infinite loopswhile (true) { /* ❌ Runs forever */ }for (let i=0; i<10; i--) { /* ❌ Never ends */ }// 2. Off-by-one errorsfor (let i=0; i <= 5; i++) { /* Runs 6 times */ }// 3. Modifying array while loopingconst numbers = [1,2,3];for (let i=0; i<numbers.length; i++) {numbers.pop(); // ❌ Causes unexpected behavior}// 4. Using var in loopsfor (var i=0; i<5; i++) { /* i leaks out */ }console.log(i); // 5 (should use let)
Always test edge cases and consider loop termination conditions carefully.
Practical Loop Examples
// 1. Sum array elementsconst prices = [4.99, 12.50, 3.75];let total = 0;for (const price of prices) {total += price;}// 2. Find maximum valueconst scores = [88, 92, 78, 95];let max = scores[0];for (let i = 1; i < scores.length; i++) {if (scores[i] > max) max = scores[i];}// 3. Filter arrayconst numbers = [1,2,3,4,5,6];const evens = [];for (const num of numbers) {if (num % 2 === 0) evens.push(num);}
total: 21.24
max: 95
evens: [2,4,6]Interactive Loops
// For loop buttondocument.getElementById("forLoopBtn").addEventListener("click", () => {let output = "";for (let i = 1; i <= 5; i++) {output += `Iteration ${i}\n`;}document.getElementById("output").textContent = output;});// Array processing buttondocument.getElementById("arrayBtn").addEventListener("click", () => {const products = ["Laptop", "Phone", "Tablet"];let html = "<ul>";for (const product of products) {html += `<li>${product}</li>`;}html += "</ul>";document.getElementById("output").innerHTML = html;});
Your Task: Number Analyzer
Create JavaScript code that:
- Adds click handlers for all four buttons
- For each button:
- For Loop: Generate and display multiplication table (1-5)
- While Loop: Generate random numbers (1-100) until one > 90, display all attempts
- Process Array:
Display: sum, average, min, maxconst numbers = [7, 23, 14, 42, 8, 51]; - Nested Loops:Create a 4x4 grid of asterisks using nested loops:
* * * *
* * * *
* * * *
* * * *
- Use appropriate loop types for each task
- Include at least:
- One break/continue statement
- One for...of loop
- One nested loop
Challenge: For the array processing, also find and display prime numbers
Tip: For min/max, initialize with first array element