Loops let you run the same code multiple times without writing it over and over. The for loop is one of the most fundamental programming concepts—perfect for repeating tasks a specific number of times, processing arrays, and generating sequences. Let's master for loops and unlock the power of iteration!
What Is a For Loop?
A for loop repeats a block of code a specific number of times. It's like saying "do this task 10 times" or "process each item in this list."
Real-world analogy:
"FOR each student in the class, DO: check their homework."
"FOR the numbers 1 through 10, DO: print the number."
Why Use Loops?
// Without loop (repetitive!)
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
// ... imagine doing this 100 times!
// With loop (efficient!)
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5For Loop Syntax
for (initialization; condition; increment) {
// Code to repeat
}
// Example
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4The Three Parts
- Initialization:
let i = 0- Runs once at the start, creates the counter variable - Condition:
i < 5- Checked before each iteration; if false, loop stops - Increment:
i++- Runs after each iteration, updates the counter
How It Works
for (let i = 0; i < 3; i++) {
console.log("Iteration:", i);
}
// Step by step:
// 1. Initialize: i = 0
// 2. Check condition: 0 < 3? Yes → execute code
// Output: "Iteration: 0"
// 3. Increment: i++ (i becomes 1)
// 4. Check condition: 1 < 3? Yes → execute code
// Output: "Iteration: 1"
// 5. Increment: i++ (i becomes 2)
// 6. Check condition: 2 < 3? Yes → execute code
// Output: "Iteration: 2"
// 7. Increment: i++ (i becomes 3)
// 8. Check condition: 3 < 3? No → stop loopBasic For Loop Examples
Counting Up
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5
// Count from 0 to 9
for (let i = 0; i < 10; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
// Even numbers
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
// Output: 0, 2, 4, 6, 8, 10
// Multiples of 5
for (let i = 5; i <= 25; i += 5) {
console.log(i);
}
// Output: 5, 10, 15, 20, 25Counting Down
// Count down from 5 to 1
for (let i = 5; i >= 1; i--) {
console.log(i);
}
// Output: 5, 4, 3, 2, 1
// Countdown from 10
for (let i = 10; i >= 0; i--) {
console.log(i);
}
console.log("Liftoff!");
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, Liftoff!
// Count down by 2
for (let i = 10; i > 0; i -= 2) {
console.log(i);
}
// Output: 10, 8, 6, 4, 2Different Starting Points
// Start from 10
for (let i = 10; i < 15; i++) {
console.log(i);
}
// Output: 10, 11, 12, 13, 14
// Start from -5
for (let i = -5; i <= 0; i++) {
console.log(i);
}
// Output: -5, -4, -3, -2, -1, 0
// Skip by larger increments
for (let i = 0; i <= 100; i += 10) {
console.log(i);
}
// Output: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100Looping Through Arrays
One of the most common uses of for loops is processing arrays.
Basic Array Iteration
let fruits = ["apple", "banana", "orange", "grape"];
// Loop through array
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// apple
// banana
// orange
// grape
// With index
for (let i = 0; i < fruits.length; i++) {
console.log(i + ":", fruits[i]);
}
// Output:
// 0: apple
// 1: banana
// 2: orange
// 3: grapeWhy Start at 0?
let numbers = [10, 20, 30, 40, 50];
// [0] [1] [2] [3] [4] ← Array indices
console.log("Length:", numbers.length); // 5
// Loop uses indices 0 to length-1
for (let i = 0; i < numbers.length; i++) {
console.log(`Index ${i} = ${numbers[i]}`);
}
// Index 0 = 10
// Index 1 = 20
// Index 2 = 30
// Index 3 = 40
// Index 4 = 50
// WRONG: This would error on last iteration
// for (let i = 0; i <= numbers.length; i++)
// numbers[5] is undefined!Arrays are zero-indexed: First element is at index 0, last element is at index length - 1. Always use i < array.length not i <= array.length.
Processing Array Elements
// Sum all numbers
let numbers = [5, 10, 15, 20, 25];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum:", sum); // 75
// Find maximum
let max = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
console.log("Max:", max); // 25
// Create new array with doubled values
let doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
console.log("Doubled:", doubled); // [10, 20, 30, 40, 50]
// Count specific items
let fruits = ["apple", "banana", "apple", "orange", "apple"];
let appleCount = 0;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i] === "apple") {
appleCount++;
}
}
console.log("Apples:", appleCount); // 3Nested Loops
You can put loops inside loops—useful for working with multi-dimensional data or generating patterns.
Basic Nested Loop
// Outer loop runs 3 times
for (let i = 1; i <= 3; i++) {
// Inner loop runs 3 times for EACH outer iteration
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
// i=2, j=2
// i=2, j=3
// i=3, j=1
// i=3, j=2
// i=3, j=3
// Total iterations: 3 × 3 = 9Multiplication Table
// Create multiplication table
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(`${i} × ${j} = ${i * j}`);
}
console.log("---");
}
// Output:
// 1 × 1 = 1
// 1 × 2 = 2
// 1 × 3 = 3
// ...
// 5 × 5 = 25Pattern Generation
// Star pattern
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "* ";
}
console.log(row);
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
// Number pattern
for (let i = 1; i <= 4; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += j + " ";
}
console.log(row);
}
// Output:
// 1
// 1 2
// 1 2 3
// 1 2 3 4Processing 2D Arrays
// 2D array (array of arrays)
let grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Loop through rows
for (let i = 0; i < grid.length; i++) {
// Loop through columns in each row
for (let j = 0; j < grid[i].length; j++) {
console.log(`[${i}][${j}] = ${grid[i][j]}`);
}
}
// Calculate sum of all elements
let total = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
total += grid[i][j];
}
}
console.log("Total:", total); // 45Watch out: Nested loops multiply iterations! A loop inside a loop inside a loop (3 levels) with 10 iterations each runs 1,000 times total. Use nested loops carefully for performance.
Common Loop Patterns
Pattern 1: Accumulation
// Sum numbers
let numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum:", sum); // 150
// Build a string
let words = ["Hello", "world", "from", "JavaScript"];
let sentence = "";
for (let i = 0; i < words.length; i++) {
sentence += words[i];
if (i < words.length - 1) {
sentence += " "; // Add space except after last word
}
}
console.log(sentence); // "Hello world from JavaScript"
// Count occurrences
let items = ["a", "b", "a", "c", "a", "b"];
let counts = {};
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (counts[item]) {
counts[item]++;
} else {
counts[item] = 1;
}
}
console.log(counts); // { a: 3, b: 2, c: 1 }Pattern 2: Finding Elements
let numbers = [3, 7, 12, 5, 9, 15];
// Find first number > 10
let found = null;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 10) {
found = numbers[i];
break; // Stop once found
}
}
console.log("First > 10:", found); // 12
// Find index of element
let searchValue = 9;
let index = -1;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === searchValue) {
index = i;
break;
}
}
console.log("Index of 9:", index); // 4
// Check if all elements meet condition
let allPositive = true;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
allPositive = false;
break;
}
}
console.log("All positive:", allPositive); // truePattern 3: Filtering
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Get even numbers
let evens = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evens.push(numbers[i]);
}
}
console.log("Even numbers:", evens); // [2, 4, 6, 8, 10]
// Get numbers greater than 5
let large = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 5) {
large.push(numbers[i]);
}
}
console.log("Numbers > 5:", large); // [6, 7, 8, 9, 10]Pattern 4: Transformation
let numbers = [1, 2, 3, 4, 5];
// Square each number
let squared = [];
for (let i = 0; i < numbers.length; i++) {
squared.push(numbers[i] ** 2);
}
console.log("Squared:", squared); // [1, 4, 9, 16, 25]
// Convert to uppercase
let words = ["hello", "world"];
let uppercase = [];
for (let i = 0; i < words.length; i++) {
uppercase.push(words[i].toUpperCase());
}
console.log("Uppercase:", uppercase); // ["HELLO", "WORLD"]
// Add tax to prices
let prices = [10, 20, 30];
let withTax = [];
let taxRate = 0.08;
for (let i = 0; i < prices.length; i++) {
withTax.push(prices[i] * (1 + taxRate));
}
console.log("With tax:", withTax); // [10.8, 21.6, 32.4]Common For Loop Mistakes
1. Off-by-One Errors
let array = [1, 2, 3, 4, 5];
// WRONG: Goes one past array length
for (let i = 0; i <= array.length; i++) {
console.log(array[i]); // Last iteration: undefined!
}
// RIGHT: Stops before length
for (let i = 0; i < array.length; i++) {
console.log(array[i]); // All elements accessed correctly
}
// WRONG: Misses first element
for (let i = 1; i < array.length; i++) {
console.log(array[i]); // Starts at index 1, skips 0
}
// RIGHT: Start at 0
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}2. Infinite Loops
// WRONG: Never increments
// for (let i = 0; i < 5; ) {
// console.log(i); // Infinite loop! Never stops
// }
// WRONG: Condition always true
// for (let i = 0; i >= 0; i++) {
// console.log(i); // Infinite loop! i is always >= 0
// }
// WRONG: Incrementing wrong direction
// for (let i = 0; i < 5; i--) {
// console.log(i); // Infinite loop! i gets more negative
// }
// RIGHT
for (let i = 0; i < 5; i++) {
console.log(i); // Stops at 5
}3. Modifying Array While Looping
let numbers = [1, 2, 3, 4, 5];
// DANGEROUS: Modifying array during iteration
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
numbers.splice(i, 1); // Removes element
// Now indices shift, might skip elements!
}
}
// BETTER: Loop backwards when removing
for (let i = numbers.length - 1; i >= 0; i--) {
if (numbers[i] % 2 === 0) {
numbers.splice(i, 1);
}
}
// BEST: Create new array
let odds = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) {
odds.push(numbers[i]);
}
}4. Variable Scope Issues
// WRONG: Using var (function scope)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (not 0, 1, 2!)
// RIGHT: Using let (block scope)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2
// Always use 'let' in for loops!Practical Examples
Example 1: Grade Calculator
function calculateAverage(scores) {
let sum = 0;
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
function getGrades(students) {
let results = [];
for (let i = 0; i < students.length; i++) {
let avg = calculateAverage(students[i].scores);
let grade;
if (avg >= 90) grade = "A";
else if (avg >= 80) grade = "B";
else if (avg >= 70) grade = "C";
else if (avg >= 60) grade = "D";
else grade = "F";
results.push({
name: students[i].name,
average: avg.toFixed(1),
grade: grade
});
}
return results;
}
let students = [
{ name: "Alice", scores: [95, 92, 88, 90] },
{ name: "Bob", scores: [78, 85, 80, 82] },
{ name: "Charlie", scores: [65, 70, 68, 72] }
];
console.log(getGrades(students));
// [
// { name: "Alice", average: "91.3", grade: "A" },
// { name: "Bob", average: "81.3", grade: "B" },
// { name: "Charlie", average: "68.8", grade: "D" }
// ]Example 2: Shopping Cart Total
function calculateCartTotal(items) {
let subtotal = 0;
// Calculate subtotal
for (let i = 0; i < items.length; i++) {
subtotal += items[i].price * items[i].quantity;
}
// Apply tax
let tax = subtotal * 0.08;
// Shipping: free over $50
let shipping = subtotal >= 50 ? 0 : 5.99;
let total = subtotal + tax + shipping;
return {
subtotal: subtotal.toFixed(2),
tax: tax.toFixed(2),
shipping: shipping.toFixed(2),
total: total.toFixed(2)
};
}
let cart = [
{ name: "T-Shirt", price: 19.99, quantity: 2 },
{ name: "Jeans", price: 49.99, quantity: 1 },
{ name: "Socks", price: 9.99, quantity: 3 }
];
console.log(calculateCartTotal(cart));
// {
// subtotal: "119.94",
// tax: "9.60",
// shipping: "0.00",
// total: "129.54"
// }For Loop Practice
Experiment with different loop patterns
console.log() to see your output in the console above.Key Takeaways
- For loops repeat code a specific number of times
- Three parts: initialization, condition, increment
- Always use
letfor loop variables, notvar - Use
i < array.lengthnoti <= array.length - Access array elements with
array[i] - Nested loops multiply iterations
- Use
i++to increment,i--to decrement - Common patterns: accumulation, finding, filtering, transformation
- Watch out for off-by-one errors and infinite loops
- Loops are essential for processing arrays and generating sequences
What's Next?
You now know how to use for loops to repeat code and process arrays! For loops are one of the most fundamental programming concepts you'll use constantly.
In the next lesson, we'll learn about While and Do-While Loops—condition-based loops that repeat as long as a condition is true. Perfect for situations where you don't know in advance how many times to loop!
💪 Practice Challenge:
Before moving on, try creating:
- A function that finds the sum and average of an array of numbers
- A function that reverses an array using a loop
- A multiplication table generator (1-10)
- A function that finds all prime numbers up to N
- A pattern generator that creates a pyramid of asterisks
Test Your Understanding
How many times will this loop execute?
for (let i = 0; i < 5; i++) {
console.log(i);
}