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

codeTap to expand ⛶
1// Classic for loop
2for (let i = 0; i < 5; i++) {
3 console.log(i); // 0, 1, 2, 3, 4
4}
5
6// while loop
7let count = 0;
8while (count < 3) {
9 console.log(count); // 0, 1, 2
10 count++;
11}
12
13// do...while (runs at least once)
14let input;
15do {
16 input = "valid"; // simulating input
17} while (input !== "valid");
18
19// for...of — iterates VALUES (arrays, strings)
20const fruits = ["apple", "banana", "cherry"];
21for (const fruit of fruits) {
22 console.log(fruit); // "apple", "banana", "cherry"
23}
24
25// 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}
30
31// ⚠️ for...in on arrays — DON'T DO THIS
32const arr = [10, 20, 30];
33for (const index in arr) {
34 console.log(typeof index); // "string"! Keys are always strings
35}
36
37// Loop control: break and continue
38for (let i = 0; i < 10; i++) {
39 if (i === 3) continue; // Skip 3
40 if (i === 7) break; // Stop at 7
41 console.log(i); // 0, 1, 2, 4, 5, 6
42}
43
44// 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:

  1. Write a loop that prints a multiplication table for a given number
  2. Use for...of to count vowels in a string
  3. Use for...in to list all properties of a nested object
  4. Write a function that finds the first duplicate in an array using a loop
  5. Create a pattern printer: for n=5, print a right triangle of stars

⚠️ Common Mistakes

  • Using for...in on arrays — it iterates string keys, includes inherited properties, and doesn't guarantee order

  • Infinite loops — forgetting to update the loop variable (while(true) without a break)

  • Off-by-one errors — using <= vs < or starting from 1 instead of 0

  • Modifying an array while iterating over it — can skip elements or cause infinite loops

  • Not knowing that for...of works 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.