JavaScript Roadmap — Day 12: Loops

 

JavaScript · Day 12 of 180 · Beginner Phase

Loops — for, while, for...of, for...in

Loops are how you make JavaScript do the same thing many times without repeating yourself. Master all five loop types and know exactly when to use each one.

Day 12 / 180
Beginner Phase
🕐 13 min read
💻 6 code examples
🎯 3 practice tasks

Imagine you are building a shopping app. You need to display 100 products. Without loops your code would look like this:

Without loops — painful
// Without loops — imagine doing this 100 times
console.log(products[0]);
console.log(products[1]);
console.log(products[2]);
// ... 97 more lines

A loop solves this in 3 lines. It repeats a block of code automatically — as many times as you need. This is one of the most fundamental concepts in all of programming. Every language has loops. Every program uses them.

1. Why Loops? — The Big Picture

JavaScript has 5 loop types. Each one is designed for a specific situation. Knowing which one to use — and when — is what separates beginners from professional developers:

Loop Best Used For When to Use
for Known number of times Counting, indexes
while Unknown number of times Wait for condition
do...while Run at least once User input validation
for...of Arrays and iterables Modern array looping
for...in Object properties Loop over object keys

2. for Loop — The Classic

The for loop is the most used loop in JavaScript. Use it when you know exactly how many times you want to repeat something. It has three parts — initializer, condition, and increment:

JavaScript — for Loop
// Basic for loop
for (let i = 0; i < 5; i++) {
  console.log(i); // 0 1 2 3 4
}

// Loop through an array
const fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// apple banana mango

// Loop backwards
for (let i = fruits.length - 1; i >= 0; i--) {
  console.log(fruits[i]);
}
// mango banana apple

// Loop with step — every 2nd item
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0 2 4 6 8 10
}

3. while Loop — When You Don't Know How Many Times

The while loop keeps running as long as a condition is true. Use it when you do not know in advance how many iterations you need — like waiting for user input or processing data until a condition is met:

JavaScript — while Loop
// Basic while loop
let count = 0;
while (count < 5) {
  console.log(count); // 0 1 2 3 4
  count++;
}

// Real world — keep asking until valid input
let password = "";
let attempts = 0;

while (password !== "pakistan123" && attempts < 3) {
  password = "wrongpass"; // simulate user input
  attempts++;
  console.log(`Attempt ${attempts}: Wrong password`);
}
console.log("Too many attempts!");

// ⚠️ Always make sure condition becomes false
// or loop runs forever — infinite loop!

🔥 Infinite Loop Warning: If the while condition never becomes false — your program freezes forever. Always make sure something inside the loop eventually makes the condition false. This is the most common beginner mistake with while loops.

4. do...while — Run at Least Once

The do...while loop is like while — but it always runs the code block at least once before checking the condition. Perfect for menus and input validation:

JavaScript — do...while Loop
// do...while — runs at least once
let num = 10;

do {
  console.log("This runs at least once!");
  num++;
} while (num < 5); // condition false — but ran once

// while vs do...while comparison
let x = 10;

// while — never runs (10 is not < 5)
while (x < 5) {
  console.log("while"); // never prints
}

// do...while — runs once even though false
do {
  console.log("do while"); // prints once!
} while (x < 5);

5. for...of — Modern Array Looping 🔥

for...of was added in ES6 and is now the preferred way to loop over arrays, strings, and other iterables. It is cleaner and more readable than the classic for loop for most use cases:

JavaScript — for...of Loop
// Loop over array — clean and simple
const skills = ["JavaScript", "React", "Node.js"];

for (const skill of skills) {
  console.log(skill);
}
// JavaScript React Node.js

// Loop over a string
for (const char of "Waheed") {
  console.log(char);
}
// W a h e e d

// With index — use entries()
for (const [index, skill] of skills.entries()) {
  console.log(`${index + 1}. ${skill}`);
}
// 1. JavaScript  2. React  3. Node.js

// Real world — process cart items
const cart = [
  { name: "Shirt", price: 1500 },
  { name: "Pants", price: 2500 },
  { name: "Shoes", price: 3500 }
];
let total = 0;
for (const item of cart) {
  total += item.price;
  console.log(`${item.name}: Rs${item.price}`);
}
console.log(`Total: Rs${total}`); // Total: Rs7500
Pro Tip #1 — for...of is the modern standard
In modern JavaScript and React codebases for...of is preferred over classic for loops for arrays. It is cleaner, more readable, and less error prone — no index management, no off-by-one errors. Use it whenever you do not need the index.
Pro Tip #2 — for...of vs forEach
Both loop over arrays but for...of supports break and continueforEach does not. If you need to stop early — use for...of. If you just need to run a function on each item — forEach is fine.
Pro Tip #3 — for...of does NOT work on objects
for...of only works on iterables — arrays, strings, Maps, Sets. It does NOT work on plain objects. For objects use for...in or Object.entries() with for...of.

6. for...in — Loop Over Object Properties

for...in loops over the keys of an object. It is specifically designed for objects — not arrays:

JavaScript — for...in Loop
const developer = {
  name:       "Waheed",
  city:       "Faisalabad",
  experience: 2,
  skills:     5
};

// Loop over keys
for (const key in developer) {
  console.log(key);
}
// name city experience skills

// Access values using key
for (const key in developer) {
  console.log(`${key}: ${developer[key]}`);
}
// name: Waheed
// city: Faisalabad
// experience: 2
// skills: 5

// Modern alternative — Object.entries()
for (const [key, value] of Object.entries(developer)) {
  console.log(`${key}: ${value}`);
}

7. break & continue — Control Your Loops

Two keywords that give you fine-grained control over loop execution. break stops the loop completely. continue skips the current iteration and moves to the next one:

JavaScript — break & continue
// break — stop loop completely
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0 1 2 3 4
}

// continue — skip this iteration
for (let i = 0; i < 6; i++) {
  if (i === 3) continue;
  console.log(i); // 0 1 2 4 5 (3 skipped)
}

// Real world — find first match
const users = [
  { name: "Ali",    active: false },
  { name: "Waheed", active: true  },
  { name: "Sara",   active: true  }
];

for (const user of users) {
  if (!user.active) continue; // skip inactive
  console.log(`Active: ${user.name}`);
}
// Active: Waheed
// Active: Sara

// break — stop when found
for (const user of users) {
  if (user.active) {
    console.log(`First active: ${user.name}`);
    break; // stop after first match
  }
}
// First active: Waheed

8. Try It Yourself

Edit the code and click Run Code. Try changing values and see how each loop behaves differently!

✏️ Try it Yourself — All Loops
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!

9. Practice Tasks

Task 1 — Easy: Multiplication Table

Use a for loop to print the multiplication table of any number from 1 to 10. Example for 5: "5 x 1 = 5", "5 x 2 = 10" ... "5 x 10 = 50".

Task 2 — Medium: Shopping Cart

Create an array of 5 products with name and price. Use for...of to loop through them. Use continue to skip products over Rs3000. Calculate and print the total of remaining products only.

Task 3 — Hard: FizzBuzz

Classic interview question — loop from 1 to 30. Print "Fizz" if divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, otherwise print the number. Use % operator and if/else inside a for loop.

Next Lesson
Day 13 — Functions
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts