Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 04

Day 4: Loops: for, while, for…of

⏱ 80 min📶 Beginner🎯 100% self-study
Day 4 / 30

✅ 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

JavaScript
// for (start; keep going while…; after each round)
for (let i = 1; i <= 5; i++) {
  console.log(`9 × ${i} = ${9 * i}`);
}
9 × 1 = 9 9 × 2 = 18 9 × 3 = 27 9 × 4 = 36 9 × 5 = 45
let i = 1 – runs once at the starti <= 5 – checked before every round; false → stopbody runsi++ – runs after every round, then check again
How a for loop works

for…of: the easiest way through a list

JavaScript
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();
Total of one kg each: 2750 Average price: 687.5 G h e w a r
LoopBest 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…inThe keys of an object (not for arrays)
whileUnknown number of rounds – until a condition changes
do…whileRun at least once (show a menu, then ask again)
array.forEach / mapFunctional style – Day 8

while and do…while

JavaScript
// 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
Goal reached in 13 months with ₹20100 Attempt 1
⚠️ Infinite loops freeze the page

If 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

JavaScript
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');
}
ok 450 skip invalid 0 ok 1200 skip invalid -50 big order found: 3000 → call the manager, stop checking kaju available ghewar available rasmalai SOLD OUT

Nested loops: patterns and tables

JavaScript
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'}`);
}
🍬 🍬🍬 🍬🍬🍬 🍬🍬🍬🍬 Aarav 4/5 ✅ Riya 5/5 ✅ Kabir 2/5 ⚠️ low

Real task: render a multiplication table on the page

HTML + JavaScript
<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>
▶  A loop builds 10 list items

🏅 Job skills unlocked today

✔ Repeat work with for and while✔ Walk through arrays with for…of and objects with for…in✔ Control loops with break and continue✔ Use nested loops for tables and reports

Practice tasks

🏋️ Practice – do it yourself

Task 1: Print all even numbers from 2 to 20 and their sum.
Show solution
JavaScript
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);
2, 4, 6, 8, 10, 12, 14, 16, 18, 20 Sum: 110
Task 2: Given marks [45, 78, 32, 91, 66], count how many passed (≥ 33) and find the highest – using one loop.
Show solution
JavaScript
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}`);
Passed: 4/5, highest: 91
Task 3: Print a pyramid of * with 5 rows using nested loops (centre it with spaces).

Quick quiz

🧠 Quick Quiz – test yourself

1. How many times does for (let i = 0; i < 5; i++) run?
0,1,2,3,4.
2. Best loop for every value of an array?
for…in gives keys.
3. continue…
break stops.
4. A do…while loop runs at least…
Check comes after.
5. The page freezes after your loop. Most likely?
Infinite loop.

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.
➡️ Next

Day 5: functions – package logic into reusable pieces: GST, EMI and discount calculators.

Frequently Asked Questions

Which loop is fastest?
For everyday app code the difference is negligible; choose the most readable loop. Optimise only after measuring.
What is process.stdout.write?
A Node.js way to print without a new line, used here only for the demo. In browsers use console.log or build a string first.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 5: Functions, Arrow Functions & Scope Your progress: 4 / 30 (13%) · Lesson 5 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free