Loops — for, while, for...of, for...in

পাঁচ ধরনের loop — সঠিকটা বেছে নিন

~30 min Beginner 14 practice problems Live runner

1. The Five Loop Forms

LoopBest For
forCounting with an index
whileRepeat until a condition fails
do...whileRun at least once, then check
for...ofValues of any iterable (Array, String, Map, Set)
for...inEnumerable keys of an object (avoid on arrays)

2. Classic for

classic.js
const arr = ["Arif", "Karim", "Nusrat"];
for (let i = 0; i < arr.length; i++) {
    console.log(i, arr[i]);
}

// Reverse
for (let i = arr.length - 1; i >= 0; i--) {
    console.log(arr[i]);
}

// Step by 2
for (let i = 0; i < 10; i += 2) console.log(i);
Classic for তিনটি অংশ — initializer, condition, update। যখনই index দরকার, এটি ব্যবহার করুন।

3. while & do...while

while.js
let n = 10;
while (n > 0) {
    console.log(n);
    n--;
}

// do...while runs at least once
let tries = 3;
do {
    console.log("attempt", tries);
    tries--;
} while (tries > 0);

4. for...of — Values of an Iterable

forof.js
const names = ["Arif", "Karim"];
for (const n of names) console.log(n);

for (const ch of "abc") console.log(ch);

// With index using entries()
for (const [i, v] of names.entries()) {
    console.log(i, v);
}

// Map and Set are iterable too
const m = new Map([["a", 1], ["b", 2]]);
for (const [k, v] of m) console.log(k, v);

5. for...in — Object Keys (Use With Care)

forin.js
const user = { name: "Arif", age: 22, city: "Dhaka" };
for (const key in user) {
    console.log(key, ":", user[key]);
}

// Better — Object.keys/values/entries
Object.entries(user).forEach(([k, v]) => console.log(k, v));

// NEVER use for...in on arrays — it walks indexes AS STRINGS
// and includes inherited enumerable props.
The big rule for...of = values, for...in = keys. Don't use for...in on arrays.

6. break, continue & Labels

break.js
// break — exit the loop
for (let i = 0; i < 10; i++) {
    if (i === 5) break;
    console.log("break:", i);
}

// continue — skip to next iteration
for (let i = 0; i < 5; i++) {
    if (i % 2 === 0) continue;
    console.log("continue:", i);
}

// labels — break out of nested loops (rare)
outer: for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (i === 1 && j === 2) break outer;
        console.log(i, j);
    }
}

7. The Modern Replacement: Array Methods

For most array work in 2026, prefer map, filter, reduce, some, every, find, forEach. They are short, declarative, and bug-resistant.

modern.js
const nums = [1, 2, 3, 4, 5];

const doubled  = nums.map(n => n * 2);
const evens    = nums.filter(n => n % 2 === 0);
const sum      = nums.reduce((a, b) => a + b, 0);
const hasBig   = nums.some(n => n > 3);
const allSmall = nums.every(n => n < 100);

console.log({ doubled, evens, sum, hasBig, allSmall });

8. Glossary (শব্দকোষ)

TermMeaningবাংলায়
IterationRepeating an operation over a sequence of values.একই কাজ একটি sequence-এর প্রতিটি item-এ চালানো।
IterableAn object that defines how to iterate it (Array, String, Map, Set).যে object-কে iterate করা যায় (Array/String/Map/Set)।
for...ofLoops over values of an iterable.Iterable-এর value-গুলোর উপর loop চালায়।
for...inLoops over keys (string) of an object — avoid on arrays.Object-এর key-এর উপর loop — array-তে ব্যবহার করবেন না।
breakExit the nearest loop immediately.সবচেয়ে কাছের loop থেকে বের হয়ে যায়।
continueSkip the rest of this iteration; go to the next.এই iteration-এর বাকিটা skip করে পরের iteration-এ যায়।
LabelNamed loop tag, used with break/continue to escape nested loops.Nested loop থেকে বের হতে নাম দেওয়া loop।
Higher-order methodArray methods (map/filter/reduce) that take a function.Function নেয় এমন array method।
একনজরে: Index দরকার হলে classic for; value-এর উপর iterate করলে for...of; object-এর key-এর জন্য for...in (array-তে নয়)। বেশিরভাগ array কাজে for-loop-এর বদলে map/filter/reduce-ই আধুনিক default — কোড পরিষ্কার ও bug-প্রতিরোধী।

9. Practice Problems

  1. Print the sum of 1 to 100 using a classic for.
    ✨ Show Answer
    a1.js
    let s = 0;
    for (let i = 1; i <= 100; i++) s += i;
    console.log(s);  // 5050
  2. Same problem with reduce.
    ✨ Show Answer
    a2.js
    const sum = Array.from({ length: 100 }, (_, i) => i + 1)
        .reduce((a, b) => a + b);
    console.log(sum);
  3. Print only the odd numbers between 1 and 20.
    ✨ Show Answer
    a3.js
    for (let i = 1; i <= 20; i++)
        if (i % 2) console.log(i);
  4. Iterate over a Bangla string with for...of and print each character.
    ✨ Show Answer
    a4.js
    for (const c of "হ্যালো") console.log(c);
  5. Walk an object's keys with for...in and print key/value pairs.
    ✨ Show Answer
    a5.js
    const u = { a: 1, b: 2, c: 3 };
    for (const k in u) console.log(k, u[k]);
  6. Find the first number greater than 10 in an array using for...of + break.
    ✨ Show Answer
    a6.js
    const arr = [3, 7, 9, 15, 21];
    let hit = null;
    for (const x of arr) {
        if (x > 10) { hit = x; break; }
    }
    console.log(hit);
  7. Same problem using find.
    ✨ Show Answer
    a7.js
    const arr = [3, 7, 9, 15, 21];
    console.log(arr.find(x => x > 10));
  8. Print a 5×5 grid of (i, j) pairs using nested loops.
    ✨ Show Answer
    a8.js
    for (let i = 0; i < 5; i++)
        for (let j = 0; j < 5; j++)
            console.log(`(${i},${j})`);
  9. Use a labeled break to stop both loops when product > 50.
    ✨ Show Answer
    a9.js
    outer: for (let i = 1; i <= 10; i++)
        for (let j = 1; j <= 10; j++) {
            if (i * j > 50) {
                console.log("hit:", i, j);
                break outer;
            }
        }
  10. Compute factorial of 10 with while.
    ✨ Show Answer
    a10.js
    let n = 10, f = 1;
    while (n > 1) f *= n--;
    console.log(f);   // 3628800
  11. Why is for...in bad for arrays?
    ✨ Show Answer

    Answer: for...in iterates string-keyed enumerable properties — including indexes (as strings, not numbers), prototype-chain additions, and any properties someone monkey-patched onto Array.prototype. Order is also not guaranteed for purely-numeric keys in older engines. Use for...of for values or a classic for when you need numeric indexes.

  12. Use Object.entries + for...of with destructuring to print object pairs.
    ✨ Show Answer
    a12.js
    const u = { name: "Arif", age: 22, city: "Dhaka" };
    for (const [k, v] of Object.entries(u)) {
        console.log(`${k} → ${v}`);
    }
  13. Build the multiplication table for 7 (1×7=7 ... 10×7=70).
    ✨ Show Answer
    a13.js
    for (let i = 1; i <= 10; i++)
        console.log(`${i} × 7 = ${i * 7}`);
  14. Run a do-while that asks for guesses (use a fixed array as input) until the right one — log each guess.
    ✨ Show Answer
    a14.js
    const answer = 7;
    const guesses = [3, 5, 7, 9];
    let i = 0, g;
    do {
        g = guesses[i++];
        console.log("guess:", g);
    } while (g !== answer && i < guesses.length);

Summary — Module 10

Five loop forms — pick the right one. Use for...of for values of iterables, for...in for object keys (never arrays), classic for when you need an index, while/do...while for condition-driven loops. For most array work, prefer map/filter/reduce.

for...of = values, for...in = keys। Array-এ for...in ব্যবহার করবেন না। Modern JS-এ array method (map/filter/reduce) অগ্রাধিকার।

Next Module → Functions — declaration, expression, arrow।