Loops & Iteration: for, while & for...of
1. Simple Definition
Jab hume kisi code block ko bar-bar repeat karna hota hai (jaise 100 products ki list screen par render karna, ya database se aayi 50 emails bhejna), tab hum Loops use karte hain. Loops ek specific condition fulfill hone tak code ko automatically bar-bar run karte hain.
2. Real-Life Analogy
Trainer ne kaha: "Shuruat lap 1 se karo (Initialise), jab tak 5 laps na ho jayein dodte raho (Condition), aur har lap ke baad counter 1 badhao (Increment)." Agar aap thak jao aur ruk jao, wo break hai; agar ek lap me shoes ka feeta bandhne ke liye pause lo aur agla lap shuru karo, wo continue hai!
3. Why Do We Need It?
Bina loops ke agar aapko 100 bar "Hello" print karna ho, toh 100 lines ka code likhna padega. Loops se wahi kaam sirf 3 lines me ho jata hai.
4. Syntax & Loop Types
// 1. Classic for loop (Index based)
for (let i = 0; i < 5; i++) {
console.log("Count:", i);
}
// 2. Modern for...of loop (Best for Arrays!)
const fruits = ["Apple", "Mango", "Banana"];
for (const fruit of fruits) {
console.log("Fruit:", fruit);
}
// 3. while loop (Condition based)
let energy = 3;
while (energy > 0) {
console.log("Working... Energy left:", energy);
energy--;
}
// 4. for...in loop (For Object Keys)
const user = { name: "Amit", city: "Delhi" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
5. Basic Example (break and continue)
for (let i = 1; i <= 6; i++) {
if (i === 3) {
console.log("Skipping 3! (continue)");
continue; // Agle number par jump karega
}
if (i === 5) {
console.log("Stopping loop at 5! (break)");
break; // Loop ko turant terminate karega
}
console.log("Number:", i);
}
6. Output / Expected Result
7. Code Explanation
for (initialization; condition; update): 3 steps ka standard loop cycle.for...of: ES6 standard jo directly array ke Values nikalta hai bina indexike jhanjhat ke.for...in: Objects ke Keys iterate karne ke liye.break: Poore loop ko turant kill/exit kar deta hai.continue: Current iteration ko skip karke seedha agle round par jump karta hai.
8. Real-World Example
Ecommerce cart me sabhi items ki prices loop karke Grand Total calculate karna: for (const item of cart) { total += item.price; }.
9. The Infinite Loop Disaster
Agar aap while loop me increment karna bhool gaye:
let i = 0;
while (i < 5) {
console.log(i);
// i++ bhool gaye! i hamesha 0 rahega!
}
Ye loop kabhi khatam nahi hoga, CPU 100% par chala jayega aur browser tab freeze hokar crash ho jayega!
10. Best Practices
- Arrays iterate karne ke liye classic
for (let i=0; ...)ke badle cleanfor...ofya array methods (forEach,map) use karein. - Loop variable ke liye hamesha
letuse karein,varnahi.
11. Try It Yourself
Playground me 1 se 10 tak ke even numbers (2, 4, 6, 8, 10) print karne wala loop likhein.
12. Challenge
Ek Multiplication Table generator banayein jo kisi bhi number (e.g. 7) ka 1 se 10 tak table console me print kare (7 x 1 = 7 ...).
13. Interview Questions
Answer:
• for...in: Objects ki Keys / Property names (ya array ke indices) iterate karta hai.
• for...of: Iterables (Arrays, Strings, Maps) ki actual Values iterate karta hai.
14. Quick Revision
for= Index counting.for...of= Array values.breakexits;continueskips one round.
15. FAQ
Q1. do...while loop while loop se kaise alag hai?
do...while condition check karne se pehle kam se kam ek baar code zaroor execute karta hai.
Q2. Kya string par loop chal sakta hai?
Haan! for (const char of "HELLO") { console.log(char); } har ek letter ko print karega.
Q3. forEach() aur for...of me kya difference hai?
forEach ek array method callback hai jisme aap break ya continue use nahi kar sakte. for...of me break aur continue perfectly work karte hain.
Q4. Nested loops kya hote hain?
Loop ke andar doosra loop (jaise 2D matrix ya grid coordinates print karna).
Q5. Reverse loop kaise likhein?
for (let i = 10; i > 0; i--) { ... } countdown loop banata hai.
Loops & Iteration: for, while & for...of
1. Simple Definition
Loops automate repetitive tasks by executing a block of code multiple times until a terminating condition is met. Modern JavaScript features classical for loops, while loops, and modern expressive iterators like for...of (for Arrays and iterables) and for...in (for Object keys).
2. Real-Life Analogy
"Run 5 laps around the field" (A counted for loop). "Keep running as long as your energy meter has not hit 0%" (A conditional while loop). "Stop immediately if it starts raining heavily" (A break statement)!
3. Modern Iteration: for...of vs for...in
| Loop Type | Iterates Over | Ideal Target | Example |
|---|---|---|---|
for...of |
Values directly | Arrays, Strings, Sets, Maps | for (const fruit of fruits) |
for...in |
Keys (Properties) | Plain JavaScript Objects | for (const key in user) |
4. Controlling Loop Execution: break and continue
const numbers = [1, 2, 3, 4, 5, 6];
for (const num of numbers) {
// Skip even numbers (jump to next iteration)
if (num % 2 === 0) continue;
// Stop the entire loop when reaching 5
if (num === 5) break;
console.log("Odd Number:", num); // Logs: 1, 3
}
5. Common Mistakes
If you write while (count < 5) and forget to increment count++ inside the loop body, the condition remains true forever, freezing the browser tab completely!
6. Best Practices
- Use
for...ofwhen looping through arrays instead of old indexedfor (let i = 0...). - Avoid
for...infor arrays because it iterates string keys and inherited prototype properties. - Ensure while loop update conditions are guaranteed to terminate.
7. Practice Exercise
Write a loop using for...of that calculates and logs the sum of all numbers in an array: [10, 20, 30, 40, 50].
8. Interview Questions
Answer: for...in iterates over the enumerable string indices ("0", "1", "2") rather than numeric values, and may iterate over custom properties added to Array.prototype. Always use for...of or array methods for arrays.
9. Summary / Cheat Card
- Use
for...offor array values. - Use
for...infor object keys. breakexits the loop;continueskips to next cycle.
10. FAQ
Q1. Can you break out of a forEach loop?
No! Array.prototype.forEach() cannot be stopped with break. Use a standard for...of loop if early termination is needed.