Loops & Control Flow (for, while, do-while, for-of & Patterns)
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.
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.
"use strict";
for (let number = 1; number <= 5; number++) {
console.log(number);
}
| Loop Construct | Syntax | When 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. |
"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]);
}
Loop execution ni ventane terminate chesi loop bayataki vachi vestundi.
Current iteration ni skip chesi direct ga next iteration ki jump chesthundi.
"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);
}
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!
"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);
Outer loop rows kosam, inner loop columns kosam run avthundhi:
"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);
}
- 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!
Mastering loops through 8 essential algorithm implementations:
Program 1: Print Numbers 1 to 100 (in 10-item chunks)
"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)
"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
"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!)
"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)
"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
"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
"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
"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);
}
Run this 1 to 5 number loop in our live compiler:
"use strict";
for (let number = 1; number <= 5; number++) {
console.log(number);
}