1. for Loop (Known Number of Iterations)

Example 1: Display products on an e-commerce website

const products = ["Laptop", "Phone", "Watch"];

for(let i = 0; i < products.length; i++){
    console.log(products[i]);
}

Use case: Showing all products from a list.


Step 1: Create an Array

const products = ["Laptop", "Phone", "Watch"];

This creates an array containing 3 items:

Think of it like:

products[0] = "Laptop"
products[1] = "Phone"
products[2] = "Watch"

Step 2: Start the Loop

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

Initialization

let i = 0

Start from the first item.

Current value:

i = 0

Condition

i < products.length

What is products.length?

products.length

Output:

3

Because there are 3 items in the array.

So the condition becomes:

i < 3

First Iteration

Current value:

i = 0

Check:

0 < 3

✅ True

Run:

console.log(products[i]);

Which means:

console.log(products[0]);

Output:

Laptop

Then:

i++

we use:

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

because if you later add more products:

const products = ["Laptop", "Phone", "Watch", "Tablet", "Camera"];

products.length automatically becomes 5, and the loop still works without changing the code.


2. while Loop (Unknown Number of Iterations)

Example 1: Login System

let password = "";

while(password !== "admin"){
    password = prompt("Enter Password");
}

Use case: Keep asking until the correct password is entered.


Comparing the Logic

while

let password = "";

while(password !== "admin"){
    password = prompt("Enter Password");
}

Flow:

Initialize password
      ↓
Check condition
      ↓
Ask password
      ↓
Check again

do...while

let password;

do{
    password = prompt("Enter Password");
}while(password !== "admin");

Flow:

Ask password
      ↓
Check condition
      ↓
Ask again if wrong


Simple Rule

  • while → "Check first, then run."
  • do...while → "Run first, then check."