Welcome back! 👋 In the previous lesson, you got an overview of all loop types in JavaScript. Now let's go deep on the most widely used one — the for loop!
The for loop is your go-to when you know exactly how many times you want to repeat something. It packs everything you need — start, condition, and update — into one clean line, making it easy to read and control.
Let's break it down completely!
What is a for Loop?
A for loop repeats a block of code a specific number of times. All three parts that control the loop — initialization, condition, and update — are written together in one place, making it very predictable and easy to follow.
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5Syntax
for (initialization; condition; update) {
// code to repeat
}The Three Parts Explained
1. Initialization — runs once before the loop starts. Usually declares and sets a counter variable.
let i = 0 // start counting from 02. Condition — checked before every iteration. If true, the loop body runs. If false, the loop stops.
i <= 5 // keep going while i is 5 or less3. Update — runs after every iteration. Usually increments or decrements the counter.
i++ // add 1 to i after each roundHow JavaScript Executes a for Loop
Understanding the exact execution order prevents bugs and confusion.
for (let i = 1; i <= 4; i++) {
console.log(i);
}Step by step:
- Step 1:
let i = 1→ initialize (runs once) - Step 2: Is
1 <= 4? ✅ Yes → run body → print1 - Step 3:
i++→ i becomes2 - Step 4: Is
2 <= 4? ✅ Yes → run body → print2 - Step 5:
i++→ i becomes3 - Step 6: Is
3 <= 4? ✅ Yes → run body → print3 - Step 7:
i++→ i becomes4 - Step 8: Is
4 <= 4? ✅ Yes → run body → print4 - Step 9:
i++→ i becomes5 - Step 10: Is
5 <= 4? ❌ No → exit loop
Counting Up and Down
Counting Up
for (let i = 1; i <= 10; i++) {
process.stdout.write(i + " ");
}
// Output: 1 2 3 4 5 6 7 8 9 10Counting Down
for (let i = 10; i >= 1; i--) {
process.stdout.write(i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1Custom Step Size
// Even numbers — step by 2
for (let i = 0; i <= 20; i += 2) {
process.stdout.write(i + " ");
}
// Output: 0 2 4 6 8 10 12 14 16 18 20
// Multiples of 5
for (let i = 5; i <= 50; i += 5) {
process.stdout.write(i + " ");
}
// Output: 5 10 15 20 25 30 35 40 45 50
// Counting down by 3
for (let i = 30; i >= 0; i -= 3) {
process.stdout.write(i + " ");
}
// Output: 30 27 24 21 18 15 12 9 6 3 0Looping Through an Array
One of the most common uses of the for loop — accessing each element by its index.
let fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// Output:
// 1. Apple
// 2. Banana
// 3. Mango
// 4. Grapes
// 5. OrangeLooping Backwards Through an Array
let steps = ["Start engine", "Fasten seatbelt", "Check mirrors", "Drive"];
for (let i = steps.length - 1; i >= 0; i--) {
console.log(`Step ${i + 1}: ${steps[i]}`);
}
// Output:
// Step 4: Drive
// Step 3: Check mirrors
// Step 2: Fasten seatbelt
// Step 1: Start enginebreak — Exit the Loop Early
Use break to stop the loop immediately when a condition is met — no need to keep iterating.
// Find the first negative number
let numbers = [12, 45, 7, -3, 88, -10];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] < 0) {
console.log(`First negative number: ${numbers[i]} at index ${i}`);
break; // Stop — no need to check the rest
}
}
// Output: First negative number: -3 at index 3// Stop once total exceeds budget
let prices = [200, 450, 150, 800, 300];
let budget = 900;
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
if (total > budget) {
console.log(`Over budget after item ${i + 1}! Total: ₹${total}`);
break;
}
}
// Output: Over budget after item 3! Total: ₹800... wait:
// 200+450=650, 650+150=800, 800+800=1600 → Over budget after item 4! Total: ₹1600continue — Skip an Iteration
Use continue to skip the current iteration and jump straight to the next one.
// Print only odd numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // Skip even numbers
process.stdout.write(i + " ");
}
// Output: 1 3 5 7 9// Skip invalid entries
let scores = [88, -1, 95, -1, 72, 60];
for (let i = 0; i < scores.length; i++) {
if (scores[i] === -1) continue; // Skip placeholder scores
console.log(`Student ${i + 1}: ${scores[i]} marks`);
}
// Output:
// Student 1: 88 marks
// Student 3: 95 marks
// Student 5: 72 marks
// Student 6: 60 marksNested for Loops
A for loop inside another for loop. The inner loop completes all its iterations for every single iteration of the outer loop.
Multiplication Table
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
process.stdout.write(`${i * j}\t`);
}
console.log(); // New line after each row
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25Star Pattern
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "⭐ ";
}
console.log(row);
}
// Output:
// ⭐
// ⭐ ⭐
// ⭐ ⭐ ⭐
// ⭐ ⭐ ⭐ ⭐
// ⭐ ⭐ ⭐ ⭐ ⭐Real-World Examples
Example 1: Calculate Total and Average
let marks = [85, 92, 78, 90, 88];
let total = 0;
for (let i = 0; i < marks.length; i++) {
total += marks[i];
}
let average = total / marks.length;
console.log(`Total: ${total}`);
console.log(`Average: ${average}`);
// Output:
// Total: 433
// Average: 86.6Example 2: Find Highest Score
let scores = [67, 92, 45, 88, 73, 99, 55];
let highest = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] > highest) {
highest = scores[i];
}
}
console.log(`Highest Score: ${highest} 🏆`);
// Output: Highest Score: 99 🏆Example 3: Countdown Timer
for (let i = 10; i >= 0; i--) {
if (i === 0) {
console.log("🚀 Blast off!");
} else {
console.log(`T-minus ${i}...`);
}
}
// Output:
// T-minus 10...
// T-minus 9...
// ...
// T-minus 1...
// 🚀 Blast off!Example 4: Generate a Shopping Receipt
let cart = [
{ name: "Notebook", price: 120, qty: 3 },
{ name: "Pen", price: 20, qty: 10 },
{ name: "Eraser", price: 10, qty: 5 },
{ name: "Ruler", price: 35, qty: 2 },
];
let grandTotal = 0;
console.log("===== RECEIPT =====");
for (let i = 0; i < cart.length; i++) {
let item = cart[i];
let subtotal = item.price * item.qty;
grandTotal += subtotal;
console.log(`${item.name.padEnd(12)} ₹${item.price} × ${item.qty} = ₹${subtotal}`);
}
console.log("===================");
console.log(`TOTAL: ₹${grandTotal}`);
// Output:
// ===== RECEIPT =====
// Notebook ₹120 × 3 = ₹360
// Pen ₹20 × 10 = ₹200
// Eraser ₹10 × 5 = ₹50
// Ruler ₹35 × 2 = ₹70
// ===================
// TOTAL: ₹680Common Mistakes
Mistake 1: Off-by-One Error
let items = ["A", "B", "C"]; // length = 3, valid indexes: 0, 1, 2
// ❌ Using <= instead of < — reads one index too far
for (let i = 0; i <= items.length; i++) {
console.log(items[i]);
}
// Output: A B C undefined ← Extra undefined!
// ✅ Use < items.length
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
// Output: A B C ✅Mistake 2: Infinite Loop — Forgetting the Update
// ❌ i never changes — runs forever and crashes!
for (let i = 0; i < 5; ) {
console.log(i);
// forgot i++
}
// ✅ Always include the update
for (let i = 0; i < 5; i++) {
console.log(i);
}Mistake 3: Using var Instead of let
// ❌ var leaks outside the loop scope
for (var i = 0; i < 3; i++) {
console.log(i);
}
console.log(i); // 3 — still accessible! Can cause unexpected bugs.
// ✅ let is block-scoped — stays inside the loop
for (let i = 0; i < 3; i++) {
console.log(i);
}
// console.log(i); // ❌ ReferenceError — not accessible outside ✅Mistake 4: Modifying i Inside the Loop Body
// ❌ Changing i inside the body breaks loop control
for (let i = 0; i < 5; i++) {
console.log(i);
i++; // i jumps by 2 each time — unintended!
}
// Output: 0 2 4 (skips 1, 3!)
// ✅ Only update i in the update expression
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0 1 2 3 4 ✅Practical Exercise
Create a file called for-loop.js:
// 🎯 For Loop Practice
// 1. FizzBuzz — classic programming challenge
console.log("=== FizzBuzz (1 to 20) ===");
for (let i = 1; i <= 20; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}
// 2. Multiplication table for a given number
function printTable(num) {
console.log(`\n=== Table of ${num} ===`);
for (let i = 1; i <= 10; i++) {
console.log(`${num} × ${i} = ${num * i}`);
}
}
printTable(8);
// 3. Find all prime numbers up to 50
console.log("\n=== Prime Numbers up to 50 ===");
for (let num = 2; num <= 50; num++) {
let isPrime = true;
for (let divisor = 2; divisor < num; divisor++) {
if (num % divisor === 0) {
isPrime = false;
break;
}
}
if (isPrime) process.stdout.write(num + " ");
}
console.log();
// 4. Student report card
let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 85 },
{ name: "Rahul", marks: 60 },
{ name: "Sara", marks: 45 },
{ name: "Arjun", marks: 73 },
];
console.log("\n=== Report Card ===");
for (let i = 0; i < students.length; i++) {
let s = students[i];
let grade = s.marks >= 90 ? "A" : s.marks >= 75 ? "B" : s.marks >= 60 ? "C" : "F";
console.log(`${s.name.padEnd(8)} | Marks: ${s.marks} | Grade: ${grade}`);
}Run it:
node for-loop.jsExpected Output (partial):
=== FizzBuzz (1 to 20) ===
1
2
Fizz
4
Buzz
...
FizzBuzz
=== Table of 8 ===
8 × 1 = 8
8 × 2 = 16
...
=== Prime Numbers up to 50 ===
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
=== Report Card ===
Mihir | Marks: 92 | Grade: A
Priya | Marks: 85 | Grade: BKey Takeaways
Congratulations! 🎉 You now fully understand the for loop in JavaScript.
✅ for loop is best when you know exactly how many times to repeat.
✅ Three parts in the loop header:
initialization— runs once at the startcondition— checked before every iterationupdate— runs after every iteration
✅ Counting: you can go up, down, or in any step size using i++, i--, i += n.
✅ Array looping: use i < array.length to safely iterate every element.
✅ break exits the loop early. continue skips the current iteration.
✅ Nested loops run the inner loop fully for each outer iteration — great for tables and patterns.
✅ Always use let (not var) for loop counters to keep scope clean.
Best Practices
- ✅ Always use
letfor the loop counter — nevervar - ✅ Use
< array.lengthnot<= array.lengthto avoid off-by-one errors - ✅ Never modify
iinside the loop body — only update it in the update expression - ✅ Use
breakto exit early when you have what you need — don't waste iterations - ✅ Use
continueto skip unwanted items cleanly instead of deep nesting - ✅ Keep nested loops to a maximum of 2 levels — deeper nesting hurts readability
- ✅ If you don't need the index, consider
for...ofinstead — it's cleaner
What's Next?
Great work! 🎉 You've mastered the for loop — the workhorse of JavaScript iteration.
Next up, let's explore the While Loop → — perfect for when you don't know how many times to repeat, and you just keep going until something changes.
Let's keep going! 💪