दिन 4: Loops: for, while, for…of
✅ आज आप सीखेंगे
- Loops क्यों: बिना copy-paste काम दोहराना
- Counter वाले for loops
- while और do…while
- Arrays और strings के लिए for…of, objects के लिए for…in
- break, continue, nested loops और infinite-loop bugs
🏢 असली दुनिया में
School office 40 students की attendance print करता है, दुकान bill पर 25 items जोड़ती है, coaching app 100 जवाब जाँचता है। एक ही line 100 बार लिखना संभालना असंभव है। Loop यह तीन lines में करता है – और 10 items या 10,000 के लिए एक जैसा।
for loop
// for (start; keep going while…; after each round)
for (let i = 1; i <= 5; i++) {
console.log(`9 × ${i} = ${9 * i}`);
}for…of: list में चलने का सबसे आसान तरीक़ा
const prices = [900, 650, 700, 500];
let total = 0;
for (const price of prices) {
total += price;
}
console.log('Total of one kg each:', total);
console.log('Average price:', total / prices.length);
for (const letter of 'Ghewar') {
process.stdout.write(letter + ' ');
}
console.log();| Loop | कब |
|---|---|
| for (let i = 0; i < n; i++) | जब index या अलग step चाहिए (हर दूसरा, उल्टा) |
| for…of ⭐ | Array, string, Map या Set की हर value |
| for…in | Object की keys (arrays के लिए नहीं) |
| while | Rounds की संख्या पता न हो – condition बदलने तक |
| do…while | कम से कम एक बार चलाना (menu दिखाओ, फिर पूछो) |
| array.forEach / map | Functional शैली – Day 8 |
while और do…while
// How many months to save ₹20,000 if you save ₹1,500 a month and get ₹200 bonus every 4th month?
let saved = 0, month = 0;
while (saved < 20000) {
month++;
saved += 1500;
if (month % 4 === 0) saved += 200;
}
console.log(`Goal reached in ${month} months with ₹${saved}`);
let tries = 0;
do {
tries++;
console.log('Attempt', tries);
} while (tries < 1); // runs once even though the condition is false afterwardsअगर condition कभी false न हो (i++ भूल गए या saved कभी नहीं बढ़ता), browser tab अटक जाता है। हमेशा जाँचें: loop के अंदर क्या बदलता है, और क्या वह आख़िरकार loop रोकेगा?
break, continue और for…in
const orders = [450, 0, 1200, -50, 3000, 800];
for (const amount of orders) {
if (amount <= 0) {
console.log('skip invalid', amount);
continue; // jump to the next item
}
if (amount > 2500) {
console.log('big order found:', amount, '→ call the manager, stop checking');
break; // leave the loop completely
}
console.log('ok', amount);
}
const stock = { kaju: 25, ghewar: 8, rasmalai: 0 };
for (const item in stock) {
console.log(item, stock[item] > 0 ? 'available' : 'SOLD OUT');
}Nested loops: patterns और tables
for (let row = 1; row <= 4; row++) {
let line = '';
for (let col = 1; col <= row; col++) {
line += '🍬';
}
console.log(line);
}
// attendance: 3 students × 5 days
const attendance = [
['Aarav', 'P', 'P', 'A', 'P', 'P'],
['Riya', 'P', 'P', 'P', 'P', 'P'],
['Kabir', 'A', 'P', 'A', 'P', 'A'],
];
for (const [name, ...days] of attendance) {
let present = 0;
for (const d of days) if (d === 'P') present++;
console.log(`${name.padEnd(6)} ${present}/5 ${present >= 4 ? '✅' : '⚠️ low'}`);
}असली task: page पर पहाड़ा दिखाना
<label>Table of <input id="n" type="number" value="13" style="width:70px"></label>
<button id="show">Show</button>
<ol id="list"></ol>
<script>
document.querySelector('#show').addEventListener('click', function () {
const n = Number(document.querySelector('#n').value);
let html = '';
for (let i = 1; i <= 10; i++) {
html += `<li>${n} × ${i} = <b>${n * i}</b></li>`;
}
document.querySelector('#list').innerHTML = html;
});
</script>🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
let sum = 0;
const evens = [];
for (let n = 2; n <= 20; n += 2) {
evens.push(n);
sum += n;
}
console.log(evens.join(', '));
console.log('Sum:', sum);Solution देखें
const marks = [45, 78, 32, 91, 66];
let passed = 0, highest = -Infinity;
for (const m of marks) {
if (m >= 33) passed++;
if (m > highest) highest = m;
}
console.log(`Passed: ${passed}/${marks.length}, highest: ${highest}`);Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
for…in बनाम for…of?
for…in object की enumerable property keys (strings) पर चलता है, inherited समेत – objects के लिए। for…of iterables (arrays, strings, Map, Set) की values पर। Arrays के लिए for…of।
forEach loop जल्दी कैसे रोकेंगे?
forEach से break नहीं कर सकते (throw के अलावा)। break वाला for…of लें, या जल्दी रुकने वाले methods जैसे some(), every() या find()।
सारांश
- गिनती वाली पुनरावृत्ति के लिए for (start; condition; step)।
- Array values के लिए for…of, object keys के लिए for…in।
- अज्ञात गिनती के लिए while; condition बदलती रहे।
- break रोकता है, continue छोड़ता है; nested loops tables बनाते हैं।
Day 5: functions – logic को दोबारा उपयोगी टुकड़ों में: GST, EMI और discount calculators।
