Loops & Iteration
Checking access...
Loops execute a block of code multiple times. They’re essential for working with arrays, processing data, and repeating tasks.
The for Loop
The classic loop — runs a block a specific number of times:
// Syntax: for (initialization; condition; increment)for (let i = 0; i < 5; i++) { console.log(`Iteration ${i}`);}// Output:// Iteration 0// Iteration 1// Iteration 2// Iteration 3// Iteration 4How it works:
let i = 0— runs once at the starti < 5— checked before each iteration- Body executes if condition is true
i++— runs after each iteration- Repeat from step 2
Looping Through Arrays
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) { console.log(`${i}: ${fruits[i]}`);}// Output:// 0: apple// 1: banana// 2: cherryBackwards Loop
for (let i = fruits.length - 1; i >= 0; i--) { console.log(fruits[i]);}// Output:// cherry// banana// appleThe while Loop
Runs while a condition is true — useful when you don’t know the iteration count in advance:
let count = 0;
while (count < 5) { console.log(count); count++;}// 0, 1, 2, 3, 4while with a Flag
let found = false;let attempts = 0;
while (!found && attempts < 10) { attempts++; // Simulate searching if (Math.random() > 0.7) { found = true; console.log(`Found after ${attempts} attempts`); }}
if (!found) { console.log("Not found after 10 attempts");}The do…while Loop
Always runs at least once — condition is checked after the body:
let input;do { input = prompt("Enter a number (or 'quit' to exit):"); console.log(`You entered: ${input}`);} while (input !== "quit");The for…of Loop (ES6)
Iterates over values of an iterable (arrays, strings, maps, sets):
const colors = ["red", "green", "blue"];
for (const color of colors) { console.log(color);}// red, green, blue
// Can use let for the variable if you need to reassignfor (let item of colors) { item = item.toUpperCase(); console.log(item); // RED, GREEN, BLUE}
// Works with strings toofor (const char of "hello") { console.log(char);}// h, e, l, l, oThe for…in Loop
Iterates over keys (properties) of an object:
const person = { name: "Alice", age: 30, city: "New York"};
for (const key in person) { console.log(`${key}: ${person[key]}`);}// name: Alice// age: 30// city: New YorkCaution
Don’t use for...in with arrays — it iterates over keys (which are strings “0”, “1”, “2”) and may include prototype properties. Use for...of or a standard for loop for arrays.
break and continue
break — Exit the Loop
for (let i = 0; i < 10; i++) { if (i === 5) { break; // Stop the loop entirely } console.log(i);}// 0, 1, 2, 3, 4
// Practical: find first matchconst numbers = [3, 7, 12, 5, 9, 15];let firstMatch;
for (const num of numbers) { if (num > 10) { firstMatch = num; break; // Stop searching once found }}
console.log(firstMatch); // => 12continue — Skip to Next Iteration
for (let i = 0; i < 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i);}// 1, 3, 5, 7, 9
// Practical: process only valid itemsconst items = [1, null, 3, undefined, 5, null, 7];
for (const item of items) { if (item === null || item === undefined) { continue; } console.log(item * 2);}// 2, 6, 10, 14Nested Loops
Loops inside loops create combinations:
// Multiplication table (1-3)for (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// ...etcLoop Performance Tips
// ❌ Bad: recalculates length on every iterationfor (let i = 0; i < arr.length; i++) { ... }
// ✅ Good: cache lengthfor (let i = 0, len = arr.length; i < len; i++) { ... }
// ✅ Even better: for...of is usually optimizedfor (const item of arr) { ... }Which Loop to Use
| Loop | When to Use |
|---|---|
for | Known iteration count, need index |
for...of | Iterating over array/string values (preferred for arrays) |
for...in | Iterating over object keys |
while | Unknown iteration count, condition-based |
do...while | Must run at least once |
Try It Yourself
// 1. Sum all numbers from 1 to 100 using a for looplet sum = 0;for (let i = 1; i <= 100; i++) { sum += i;}console.log(sum); // => 5050
// 2. Find the largest number in an arrayconst nums = [12, 45, 7, 89, 23, 56];let max = nums[0];for (const num of nums) { // Your code here}
// 3. Count how many vowels in a stringconst text = "hello world";let vowelCount = 0;// Your code here
// 4. Print a triangle pattern// *// **// ***// ****// *****Key Takeaways
forloops have three parts: initialization, condition, incrementfor...ofis the cleanest way to iterate over arraysfor...initerates object keys — don’t use it for arrayswhileloops run while a condition is true;do...whilealways runs at least oncebreakexits the loop entirely;continueskips to the next iteration- Use
breakto stop searching after finding a match - Cache
array.lengthin performance-sensitiveforloops - Nested loops create combinations — be aware of O(n²) performance