Lesson 1: The for Loop

Learning Objectives

By the end of this lesson, learners will:

  • Understand the purpose and structure of the for loop
  • Learn how to repeat a block of code a specific number of times
  • Be able to use a loop counter (i) to track repetitions
  • Practice using for loops to automate and simplify repetitive tasks

What Is a for Loop?

A for loop is a type of loop in JavaScript that repeats code a set number of times.

It is best used when you know exactly how many times you want to run the loop.


The Structure of a for Loop

Syntax:

for (initialization; condition; update) {
  // code to run each time
}

Breakdown:

PartExampleWhat It Does
Initializationlet i = 0Starts a loop counter (often i)
Conditioni < 5Loop runs as long as this is true
Updatei++Changes the counter (usually increases by 1)

Basic Example:

for (let i = 0; i < 3; i++) {
  console.log("Loop run #" + i);
}

Output:

Loop run #0
Loop run #1
Loop run #2

✅ The loop runs 3 times:

  • Starts at i = 0
  • Runs while i < 3
  • Increments i by 1 each time

Visual Flow of a for Loop

  1. Initialize: let i = 0
  2. Check: Is i < 3? → ✅ Yes
  3. Run the block: console.log(...)
  4. Update: i++
  5. Repeat steps 2–4 until i < 3 is ❌ false

Why Is the Counter Often Named i?

  • It stands for “index” (from math)
  • Common convention in loops
  • You can use any name (e.g. counter, step, x), but i is concise and standard

Common Use Case: Looping a Number of Times

Example: Count from 1 to 5

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Output:

1
2
3
4
5

Looping in Reverse

You can also count down:

for (let i = 5; i >= 1; i--) {
  console.log(i);
}

Output:

5
4
3
2
1

Looping with Custom Steps

You can change the step amount:

for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}

Output:

0
2
4
6
8
10

Infinite Loops (What to Avoid)

If the condition never becomes false, the loop will run forever!

❌ Example:

for (let i = 1; i > 0; i++) {
  console.log("This will never stop!");
}

⚠️ Always make sure your condition will eventually be false.


Real-World Example: Repeat a Message

for (let i = 1; i <= 3; i++) {
  console.log("Welcome to Codevisionz!");
}

Output:

Welcome to Codevisionz!
Welcome to Codevisionz!
Welcome to Codevisionz!