Loops
📖 Concept
Loops execute a block of code repeatedly until a condition is met.
for — Classic loop with initializer, condition, and increment. Best when you know the iteration count. while — Runs while a condition is true. Best when the number of iterations is unknown. do...while — Like while, but guarantees at least one execution. for...of — Iterates over iterable values (arrays, strings, Maps, Sets). Best for most array/string loops. for...in — Iterates over enumerable property KEYS of an object. Best for objects (but be careful!).
🏠 Real-world analogy: A for loop is like reading a book page by page — you know there are 300 pages. A while loop is like searching for your keys — you keep looking until you find them.
💻 Code Example
1// Classic for loop2for (let i = 0; i < 5; i++) {3 console.log(i); // 0, 1, 2, 3, 44}56// while loop7let count = 0;8while (count < 3) {9 console.log(count); // 0, 1, 210 count++;11}1213// do...while (runs at least once)14let input;15do {16 input = "valid"; // simulating input17} while (input !== "valid");1819// for...of — iterates VALUES (arrays, strings)20const fruits = ["apple", "banana", "cherry"];21for (const fruit of fruits) {22 console.log(fruit); // "apple", "banana", "cherry"23}2425// for...in — iterates KEYS (objects)26const person = { name: "Alice", age: 25, city: "NYC" };27for (const key in person) {28 console.log(`${key}: ${person[key]}`);29}3031// ⚠️ for...in on arrays — DON'T DO THIS32const arr = [10, 20, 30];33for (const index in arr) {34 console.log(typeof index); // "string"! Keys are always strings35}3637// Loop control: break and continue38for (let i = 0; i < 10; i++) {39 if (i === 3) continue; // Skip 340 if (i === 7) break; // Stop at 741 console.log(i); // 0, 1, 2, 4, 5, 642}4344// Labeled loops (rare but useful for nested loops)45outer: for (let i = 0; i < 3; i++) {46 for (let j = 0; j < 3; j++) {47 if (i === 1 && j === 1) break outer;48 console.log(i, j);49 }50}
🏋️ Practice Exercise
Mini Exercise:
- Write a loop that prints a multiplication table for a given number
- Use
for...ofto count vowels in a string - Use
for...into list all properties of a nested object - Write a function that finds the first duplicate in an array using a loop
- Create a pattern printer: for n=5, print a right triangle of stars
⚠️ Common Mistakes
Using
for...inon arrays — it iterates string keys, includes inherited properties, and doesn't guarantee orderInfinite loops — forgetting to update the loop variable (
while(true)without abreak)Off-by-one errors — using
<=vs<or starting from 1 instead of 0Modifying an array while iterating over it — can skip elements or cause infinite loops
Not knowing that
for...ofworks on any iterable (strings, Maps, Sets) but NOT plain objects
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Loops. Login to unlock this feature.