Loops & Control Flow (for, while, do-while, for-of & Patterns)

๐ŸŸจ JavaScript (ES2026+) ๐ŸŸข Lesson 8 ๐Ÿ“‚ Phase 05: Loops & Iterations ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this lesson: Why Loops ยท for ยท while ยท do...while ยท for...of ยท for...in ยท Nested Loops ยท break ยท continue ยท Infinite Loops ยท Strings & Arrays ยท Star Patterns ยท Loop Performance ยท 8 Practice Programs

Welcome to Phase 5: Loops & Iterations! In programming, repetitive tasks are automated through Loops. Rather than writing duplicate code, loops execute a block of instructions continuously until a termination condition is met. In this masterclass guide, you will master standard for loops, while loops, do...while, modern for...of (iterables) & for...in (object properties), nested loops, break/continue controllers, string/array traversal, star patterns, and solve 8 essential coding interview algorithms.

1Why Loops are Needed (DRY Principle)

Imagine 1 nunchi 100 daka numbers print cheyyali. Loop lekunte 100 lines console.log() rayalsi untundhi. Loops software development lo DRY (Don't Repeat Yourself) principle ni follow avthu, 3 lines of code tho millions of records ni process cheyyagala power ni isthayi.

JavaScript โ€” 1 to 5 Counter โ–ถ Run Code
"use strict";

for (let number = 1; number <= 5; number++) {
    console.log(number);
}
2The 5 Loop Types in JavaScript
Loop ConstructSyntaxWhen to Use?
1. for loop for (let i = 0; i < n; i++) When the exact number of iterations is known in advance.
2. while loop while (condition) { ... } When iterations depend on a dynamic condition (unknown count).
3. do...while loop do { ... } while (condition); When code must execute at least once before checking condition.
4. for...of loop for (const item of array) Iterating over values of Iterables (Arrays, Strings, Sets, Maps).
5. for...in loop for (const key in object) Iterating over Keys / Property names of an Object.
JavaScript โ€” Loop Varieties Demo โ–ถ Run Code
"use strict";

// 1. While Loop
let count = 3;
while (count > 0) {
    console.log("Countdown:", count);
    count--;
}

// 2. do...while Loop (Executes at least once)
let x = 10;
do {
    console.log("do-while executed, x is:", x);
    x++;
} while (x < 5); // False condition, but executed once!

// 3. for...of Loop (Iterating array values)
const fruits = ["๐ŸŽ Apple", "๐ŸŒ Banana", "๐Ÿฅญ Mango"];
for (const fruit of fruits) {
    console.log("Fruit:", fruit);
}

// 4. for...in Loop (Iterating object properties)
const user = { name: "Ravi", role: "Dev", city: "Hyderabad" };
for (const key in user) {
    console.log(key + " -> " + user[key]);
}
3break, continue & Infinite Loops
1. break Statement

Loop execution ni ventane terminate chesi loop bayataki vachi vestundi.

2. continue Statement

Current iteration ni skip chesi direct ga next iteration ki jump chesthundi.

JavaScript โ€” break & continue โ–ถ Run Code
"use strict";

console.log("--- continue demo (skipping 3) ---");
for (let i = 1; i <= 5; i++) {
    if (i === 3) continue; // Skip 3
    console.log("Number:", i);
}

console.log("--- break demo (stopping at 4) ---");
for (let i = 1; i <= 10; i++) {
    if (i === 4) break; // Terminate loop
    console.log("Number:", i);
}
โš ๏ธ Infinite Loop Warning

Loop update step (e.g. i++) marchipothe, condition eppatiki true gaa undi browser or server CPU 100% crash avthundhi. Always ensure the loop variable moves towards a termination boundary!

4Looping through Strings & Arrays
JavaScript โ€” String & Array Traversal โ–ถ Run Code
"use strict";

// Traversal on String
const tech = "JS2026";
for (let i = 0; i < tech.length; i++) {
    console.log("Char at " + i + ": " + tech[i]);
}

// Array sum calculation
const prices = [100, 250, 450, 800];
let totalCart = 0;
for (const price of prices) {
    totalCart += price;
}
console.log("Total Cart Amount: Rs." + totalCart);
5Nested Loops & Star / Number Patterns

Outer loop rows kosam, inner loop columns kosam run avthundhi:

JavaScript โ€” Patterns โ–ถ Run Code
"use strict";

// 1. Right Angled Star Pattern
console.log("--- Star Triangle Pattern ---");
for (let row = 1; row <= 5; row++) {
    let rowStr = "";
    for (let col = 1; col <= row; col++) {
        rowStr += "* ";
    }
    console.log(rowStr);
}

// 2. Number Pattern
console.log("--- Number Triangle Pattern ---");
for (let row = 1; row <= 5; row++) {
    let rowStr = "";
    for (let col = 1; col <= row; col++) {
        rowStr += col + " ";
    }
    console.log(rowStr);
}
6Loop Performance Basics
  • Array Length Caching: For giant arrays with $100,000+$ items, store length in variable: for (let i = 0, len = arr.length; i < len; i++).
  • Avoid DOM queries inside loop: Don't call document.getElementById() inside a loop โ€” fetch the element once outside!
7Practice Programs (All 8 Complete Solutions)

Mastering loops through 8 essential algorithm implementations:

Program 1: Print Numbers 1 to 100 (in 10-item chunks)

JavaScript โ–ถ Run Code
"use strict";

for (let i = 1; i <= 100; i += 10) {
    let line = "";
    for (let j = i; j < i + 10; j++) {
        line += j + " ";
    }
    console.log(line);
}

Program 2: Multiplication Table (5 Table)

JavaScript โ–ถ Run Code
"use strict";

let tableNum = 5;
for (let i = 1; i <= 10; i++) {
    console.log(tableNum + " x " + i + " = " + (tableNum * i));
}

Program 3: Sum of First N Numbers

JavaScript โ–ถ Run Code
"use strict";

let n = 10;
let sum = 0;
for (let i = 1; i <= n; i++) {
    sum += i;
}
console.log("Sum of first " + n + " numbers is: " + sum); // 55

Program 4: Factorial of a Number (5!)

JavaScript โ–ถ Run Code
"use strict";

let num = 5;
let fact = 1;
for (let i = 1; i <= num; i++) {
    fact *= i;
}
console.log(num + "! = " + fact); // 120

Program 5: Reverse a Number (12345 -> 54321)

JavaScript โ–ถ Run Code
"use strict";

let original = 12345;
let temp = original;
let reversed = 0;

while (temp > 0) {
    let digit = temp % 10;
    reversed = (reversed * 10) + digit;
    temp = Math.floor(temp / 10);
}

console.log("Original: " + original + " | Reversed: " + reversed);

Program 6: Prime Number Checker

JavaScript โ–ถ Run Code
"use strict";

function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}

console.log("Is 29 Prime? " + isPrime(29)); // true
console.log("Is 35 Prime? " + isPrime(35)); // false

Program 7: Fibonacci Series Generator

JavaScript โ–ถ Run Code
"use strict";

let terms = 10;
let n1 = 0, n2 = 1;
let fibSequence = [];

for (let i = 1; i <= terms; i++) {
    fibSequence.push(n1);
    let nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
}

console.log("Fibonacci (" + terms + " terms):", fibSequence.join(", "));

Program 8: Pyramid Star Pattern

JavaScript โ–ถ Run Code
"use strict";

let totalRows = 5;
for (let i = 1; i <= totalRows; i++) {
    let spaces = " ".repeat(totalRows - i);
    let stars = "*".repeat(2 * i - 1);
    console.log(spaces + stars);
}
๐Ÿ’ป Try It Yourself โ€” User Curriculum Code Example

Run this 1 to 5 number loop in our live compiler:

JavaScript โ–ถ Run Code
"use strict";

for (let number = 1; number <= 5; number++) {
    console.log(number);
}
Run Code in Our Compiler โ†’
OC
Written and reviewed by Our Compiler Technical Team ยท Updated for JavaScript ES2026+