Day 4: Loops: for, while, for…of
✅ Today you will learn
- Why loops: repeat work without copy-paste
- for loops with a counter
- while and do…while
- for…of for arrays and strings, for…in for objects
- break, continue, nested loops and infinite-loop bugs
🏢 In the real world
A school office prints attendance for 40 students, a shop totals 25 items on a bill, a coaching app checks 100 answers. Writing the same line 100 times is impossible to maintain. A loop does it in three lines – and works the same for 10 items or 10,000.
The 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: the easiest way through a 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 | Best for |
|---|---|
| for (let i = 0; i < n; i++) | When you need the index or a custom step (every 2nd, backwards) |
| for…of ⭐ | Every value of an array, string, Map or Set |
| for…in | The keys of an object (not for arrays) |
| while | Unknown number of rounds – until a condition changes |
| do…while | Run at least once (show a menu, then ask again) |
| array.forEach / map | Functional style – Day 8 |
while and 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 afterwardsIf the condition never becomes false (forgot i++ or saved never grows), the browser tab hangs. Always check: what changes inside the loop, and will it eventually stop the loop?
break, continue and 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 and 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'}`);
}Real task: render a multiplication table on the 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 unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show 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);Show 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 – test yourself
Interview corner
💼 Interview Corner
for…in vs for…of?
for…in iterates enumerable property keys (strings) of an object, including inherited ones – meant for objects. for…of iterates values of iterables (arrays, strings, Map, Set). Use for…of for arrays.
How would you stop a forEach loop early?
You cannot break out of forEach (except by throwing). Use for…of with break, or array methods that stop early like some(), every() or find().
Summary
- for (start; condition; step) for counted repetition.
- for…of for array values, for…in for object keys.
- while for unknown counts; make sure the condition changes.
- break stops, continue skips; nested loops build tables.
Day 5: functions – package logic into reusable pieces: GST, EMI and discount calculators.
