Loops in JavaScript Explained (for, while, forEach) with Examples for Beginners”

Loops in JavaScript: for, while, forEach — Complete Guide (2026)
πŸ” JavaScript Loops · Complete Guide

Loops in JavaScript:
for, while, forEach

Every loop type explained — for, while, do-while, forEach, for...of, for...in, break & continue, nested loops, performance tips, real examples, and practice questions.

⏱️ 10 min read πŸ” All Loop Types πŸ’» Code + Output πŸ‹️ Practice

What is a Loop in JavaScript? — Why Loops Are Essential

A loop is a programming structure that repeats a block of code multiple times — automatically — until a certain condition is met. Without loops, if you wanted to print numbers 1 to 100, you would have to write console.log() one hundred times. With a loop, you write it once and let JavaScript do the repetition.

Loops are one of the most fundamental tools in programming. They are used to process every item in a list, repeat an action a fixed number of times, keep running until a user gives valid input, build tables and patterns, process API data, and much more.

JavaScript has 7 different loop types, each designed for a specific situation. Understanding when to use which loop is a sign of a skilled JavaScript developer. Let's go through every one — completely from A to Z — with real code and practical examples.

for

The for Loop — The Most Common Loop in JavaScript

The for loop is the most widely used loop. It is perfect when you know exactly how many times you want to repeat something. It has three parts: initialization (starting point), condition (when to stop), and update (how to change after each run).

// Basic for loop — count 1 to 5

for (let i = 1; i <= 5; i++) {

  console.log("Count: " + i);

}

// Loop backwards — count down

for (let i = 5; i >= 1; i--) {

  console.log("Countdown: " + i);

}

// Loop through an array — most common use

const fruits = ["Apple", "Banana", "Mango", "Orange"];

for (let i = 0; i < fruits.length; i++) {

  console.log(`Fruit ${i+1}: ${fruits[i]}`);

}

// Sum of numbers using for loop

let sum = 0;

for (let i = 1; i <= 100; i++) {

  sum += i;

}

console.log("Sum 1 to 100: " + sum);  // 5050
▶ Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Countdown: 5 4 3 2 1 Fruit 1: Apple Fruit 2: Banana Fruit 3: Mango Fruit 4: Orange Sum 1 to 100: 5050
while

while Loop & do...while Loop — Condition-Based Loops

The while loop keeps running as long as a condition is true. Use it when you don't know in advance how many times the loop should run — you just know the condition that should stop it. The do...while loop is similar but guarantees the code runs at least once before checking the condition.

// while loop — runs while condition is true

let count = 1;

while (count <= 5) {

  console.log("While count: " + count);

  count++;

}

// Practical while — keep asking until valid input

let password = "";

let attempts = 0;

while (password !== "secret123" && attempts < 3) {

  password = "wrongpass";  // simulating input

  attempts++;

  console.log(`Attempt ${attempts}: Wrong password`);

}

console.log("Max attempts reached");

// do...while — runs at least ONCE, then checks condition

let num = 10;

do {

  console.log("do...while runs: " + num);

  num++;

} while (num < 5);

// Runs once even though 10 < 5 is false!

// Key difference — while may not run at all

let x = 100;

while (x < 5) {

  console.log("This never prints!");

}

console.log("While loop skipped ✅");
▶ Output
While count: 1 2 3 4 5 Attempt 1: Wrong password Attempt 2: Wrong password Attempt 3: Wrong password Max attempts reached do...while runs: 10 While loop skipped ✅
πŸ”„

forEach, for...of & for...in — Modern JavaScript Loops

ES6 introduced cleaner, more readable ways to loop through data. forEach iterates over array items and runs a callback for each. for...of is the cleanest loop for iterating over any iterable (arrays, strings, Maps, Sets). for...in loops over an object's enumerable keys.

const students = [

  { name: "Sara",  score: 85 },

  { name: "Ali",   score: 72 },

  { name: "Ahmed", score: 95 }

];

// forEach — best for arrays, has index access

students.forEach((student, index) => {

  console.log(`${index+1}. ${student.name}: ${student.score}`);

});

// for...of — cleanest syntax, works on any iterable

const colors = ["red", "green", "blue"];

for (let color of colors) {

  console.log("Color: " + color);

}

// for...of on a string — iterates each character!

for (let char of "Hello") {

  console.log(char);

}

// for...in — iterate over object KEYS

const person = { name: "Sara", age: 22, job: "Developer" };

for (let key in person) {

  console.log(`${key}: ${person[key]}`);

}

// Difference: for...of gives VALUES, for...in gives KEYS

const nums = [10, 20, 30];

for (let val of nums) console.log("of:", val);    // 10 20 30 (values)

for (let key in nums) console.log("in:", key);    // 0 1 2 (indexes)
▶ Output
1. Sara: 85 2. Ali: 72 3. Ahmed: 95 Color: red green blue H e l l o name: Sara age: 22 job: Developer of: 10 of: 20 of: 30 in: 0 in: 1 in: 2

break & continue — Controlling Loop Execution

break immediately stops the entire loop and exits it — no more iterations happen after break. continue skips the current iteration and jumps to the next one — the loop keeps running, just not for the current item. Both are essential tools for writing efficient loop logic.

// BREAK — stop loop completely

for (let i = 1; i <= 10; i++) {

  if (i === 5) {

    console.log("Found 5! Stopping loop.");

    break;   // exits the loop immediately

  }

  console.log("Number: " + i);

}

// CONTINUE — skip current, keep going

for (let i = 1; i <= 8; i++) {

  if (i % 2 === 0) continue;   // skip even numbers

  console.log("Odd: " + i);        // only prints odd numbers

}

// Practical break — find first item matching condition

const products = [

  { name: "Phone",  price: 50000, inStock: false },

  { name: "Tablet", price: 30000, inStock: true  },

  { name: "Laptop", price: 80000, inStock: true  },

];

let firstAvailable;

for (let product of products) {

  if (product.inStock) {

    firstAvailable = product;

    break;   // stop once we found first available item

  }

}

console.log("First available: " + firstAvailable.name);  // Tablet
▶ Output
Number: 1 Number: 2 Number: 3 Number: 4 Found 5! Stopping loop. Odd: 1 Odd: 3 Odd: 5 Odd: 7 First available: Tablet
[][]

Nested Loops — Loop Inside a Loop

A nested loop is a loop placed inside another loop. The inner loop runs completely for every single iteration of the outer loop. Nested loops are used for 2D data — tables, matrices, grids, multiplication tables, and any data that has rows and columns. The key is understanding that the inner loop runs fully before the outer loop moves to its next iteration.

// Multiplication table — classic nested loop example

for (let i = 1; i <= 3; i++) {

  for (let j = 1; j <= 3; j++) {

    console.log(`${i} x ${j} = ${i * j}`);

  }

  console.log("---");

}

// 2D Array (matrix) using nested loops

const matrix = [[1,2,3], [4,5,6], [7,8,9]];

for (let row of matrix) {

  console.log(row.join(" | "));

}

// Practical — loop through array of objects

const classes = [

  { name: "Class A", students: ["Sara", "Ali"] },

  { name: "Class B", students: ["Ahmed", "Zara"] }

];

for (let cls of classes) {

  console.log("πŸ“š " + cls.name);

  for (let student of cls.students) {

    console.log("   πŸ‘€ " + student);

  }

}
▶ Output
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 --- 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 --- 1 | 2 | 3 4 | 5 | 6 7 | 8 | 9 πŸ“š Class A πŸ‘€ Sara πŸ‘€ Ali πŸ“š Class B πŸ‘€ Ahmed πŸ‘€ Zara

Loop Comparison Table & Performance Tips

LoopBest Use CaseCan Break?Has Index?
forKnown count, array iteration✅ Yes✅ Yes
whileUnknown count, condition-based✅ YesManual
do...whileMust run at least once✅ YesManual
forEachArray iteration with callback❌ No✅ Yes
for...ofAny iterable — cleanest syntax✅ Yes❌ No
for...inObject keys only✅ YesKeys
Performance Tips for Loops:
• Cache array length: const len = arr.length before the loop
• Use for...of or forEach for readability on arrays
• Use for loop for maximum performance on large datasets
• Use break as soon as you find what you need — don't loop unnecessarily
• Avoid modifying the array you are looping through inside the loop

πŸ‹️ Practice Questions

Q1: Print all even numbers from 1 to 20 using a for loopAnswer: for (let i=2; i<=20; i+=2) console.log(i);
Q2: What loop runs at least once even if condition is false?Answer: do...while loop
Q3: Which keyword skips current iteration?Answer: continue
Q4: Use for...of to print all items in ["JS","Python","Go"]Answer: for (let lang of arr) console.log(lang);

✅ Complete Summary — Loops in JavaScript

🟒 for loop: Known iterations — for(let i=0; i<n; i++) — most common loop
πŸ”΅ while loop: Unknown count — runs while condition true — may skip entirely
🟑 do...while: Always runs once first — then checks condition — user input validation
🟣 forEach: Array method — callback for each item — no break support
🩡 for...of: Cleanest loop — any iterable — arrays, strings, Maps, Sets
🟠 for...in: Object keys — loops over enumerable properties — not for arrays
πŸ”΄ break: Exit loop completely · continue: Skip current iteration only
Nested loops: Inner runs fully for each outer iteration — use for tables and matrices
πŸ“Œ Important Note

The most important loops to master first are the for loop (for counted repetitions) and for...of (for iterating arrays cleanly). Once those feel natural, while, forEach, and for...in will click into place quickly. Always remember: a while (true) loop without a proper break condition will crash your program with an infinite loop. Always make sure your loop has a clear exit condition!

Comments