R
Rishtaara
JavaScript Fundamentals
Lesson 5 of 28Article16 min

for, while, do...while & break/continue

for repeats code a fixed number of times. It has start (let i = 0), condition (i < 5), and step (i++).

for Loop

for repeats code a fixed number of times. It has start (let i = 0), condition (i < 5), and step (i++).

Real-life example: Counting laps in a running ground — start at 1, stop at 10, add 1 each lap.

Classic for loop
for (let i = 1; i <= 5; i++) {
  console.log("Lap " + i);
}

while Loop

while repeats while a condition is true. Check the condition before each round.

Real-life example: Keep filling water while the bottle is not full.

while loop
let count = 3;
while (count > 0) {
  console.log(count);
  count--;
}

do...while Loop

do...while runs the body at least once, then checks the condition.

Real-life example: Taste the soup once, then decide if you need more salt.

do while
let n = 0;
do {
  console.log(n);
  n++;
} while (n < 3);

for...of Loop

for...of loops over values in arrays, strings, and other iterables. Simple and readable.

Real-life example: Hand out one textbook to each student in a line — you take each item directly.

for...of with array
const fruits = ["apple", "mango", "banana"];
for (const fruit of fruits) {
  console.log(fruit);
}

for...in Loop

for...in loops over property names (keys) of an object. Avoid it on arrays — use for...of or forEach instead.

Real-life example: Reading labels on boxes in a storeroom — you get names of boxes, not the contents one by one.

for...in with object
const user = { name: "Asha", city: "Mumbai" };
for (const key in user) {
  console.log(key + ": " + user[key]);
}

break and continue

break exits the loop early. continue skips the rest of the current round and goes to the next.

Real-life example: break — stop searching when you find your keys. continue — skip one bad apple and check the next.

break and continue
for (let i = 1; i <= 10; i++) {
  if (i === 3) continue; // skip printing 3
  if (i === 8) break;    // stop at 8
  console.log(i);
}