Skip to content

Instantly share code, notes, and snippets.

@decagondev
Last active October 22, 2025 21:10
Show Gist options
  • Save decagondev/81d9f7024b532fcaa8b98f120a59e0a6 to your computer and use it in GitHub Desktop.
Save decagondev/81d9f7024b532fcaa8b98f120a59e0a6 to your computer and use it in GitHub Desktop.

Understanding For Loops in JavaScript

A for loop in JavaScript is a way to repeat a block of code a specific number of times or until a condition is met. It’s commonly used when you know how many times you want to run the loop or need to iterate over a sequence, like numbers, elements in an array, or characters in a string. This guide breaks down the for loop into its simplest parts, focusing on the syntax like (let i = 0; i < someValue; i++), with examples to make it clear for beginners.

What is a For Loop?

A for loop runs a block of code repeatedly based on a condition. It’s structured to initialize a counter, check a condition, and update the counter after each iteration. Here’s the basic syntax:

for (initialization; condition; update) {
  // Code to execute in each iteration
}

Components of a For Loop

Let’s dissect the common example (let i = 0; i < someValue; i++):

  1. Initialization (let i = 0):

    • Sets up a counter variable (often called i, but you can name it anything).
    • Runs once before the loop starts.
    • Example: let i = 0 creates a variable i and sets it to 0, marking the starting point.
    • Purpose: Defines where the loop begins.
  2. Condition (i < someValue):

    • A test that runs before each iteration. If true, the loop’s code block runs. If false, the loop stops.
    • Example: i < someValue checks if i is less than someValue (e.g., 5).
    • Purpose: Controls how long the loop runs by defining when it should stop.
  3. Update (i++):

    • Runs after each iteration to update the counter variable.
    • Example: i++ increases i by 1 (short for i = i + 1).
    • Purpose: Moves the counter toward the condition that will eventually stop the loop.
  4. Body (the code block {}):

    • The code inside the curly braces {} runs repeatedly as long as the condition is true.
    • Example: console.log(i) could print the value of i in each iteration.
    • Purpose: Contains the actual work you want the loop to perform.

Example of a For Loop

Here’s a simple example that prints numbers from 0 to 4:

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

Output:

0
1
2
3
4

Flowchart:

graph TD
    A[Start] --> B["Initialize: let i = 0"]
    B --> C{Condition: i < 5}
    C -->|True| D["Body: console.log(i)"]
    D --> E[Update: i++]
    E --> C
    C -->|False| F[End]
Loading

How it works:

  1. Initialization: let i = 0 sets i to 0.
  2. Condition: i < 5 checks if i is less than 5. If true, the loop runs.
  3. Body: console.log(i) prints the current value of i.
  4. Update: i++ increments i by 1.
  5. Repeat steps 2–4 until i < 5 is false (when i becomes 5).

Step-by-Step Breakdown of Execution

Here’s what happens in the example above:

  • First iteration: i = 0, 0 < 5 is true, prints 0, i becomes 1.
  • Second iteration: i = 1, 1 < 5 is true, prints 1, i becomes 2.
  • Third iteration: i = 2, 2 < 5 is true, prints 2, i becomes 3.
  • Fourth iteration: i = 3, 3 < 5 is true, prints 3, i becomes 4.
  • Fifth iteration: i = 4, 4 < 5 is true, prints 4, i becomes 5.
  • Sixth attempt: i = 5, 5 < 5 is false, loop stops.

Example: Looping Over an Array

For loops are great for iterating over arrays. Here’s an example:

let fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Output:

apple
banana
orange

Flowchart:

graph TD
    A[Start] --> B["Initialize: let i = 0"]
    B --> C{Condition: i < fruits.length}
    C -->|True| D["Body: console.log(fruits[i])"]
    D --> E[Update: i++]
    E --> C
    C -->|False| F[End]
Loading

Explanation:

  • i < fruits.length uses the array’s length (3) as the condition.
  • fruits[i] accesses each element in the array using the index i.

Example: Looping Over Each Letter of a String

For loops can also iterate over each character in a string by accessing characters via their index. Here’s an example:

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

Output:

h
e
l
l
o

Flowchart:

graph TD
    A[Start] --> B["Initialize: let i = 0"]
    B --> C{Condition: i < word.length}
    C -->|True| D["Body: console.log(word[i])"]
    D --> E[Update: i++]
    E --> C
    C -->|False| F[End]
Loading

Explanation:

  • word.length gives the number of characters in the string (5 for "hello").
  • word[i] accesses each character at index i (e.g., word[0] is "h", word[1] is "e", etc.).
  • The loop runs from i = 0 to i < 5, printing each letter.

Variations and Flexibility

  • Initialization: Can use var, let, or const (if not reassigning), or skip it if the counter is defined outside.
    let i = 0;
    for (; i < 5; i++) {
      console.log(i);
    }
  • Condition: Can use any comparison, like i <= 5 or i > 0.
  • Update: Can use i-- (decrease), i += 2 (increment by 2), etc.
    for (let i = 10; i > 0; i -= 2) {
      console.log(i); // Prints 10, 8, 6, 4, 2
    }
  • Empty sections: You can omit parts, but semicolons are required.
    let i = 0;
    for (; i < 5;) {
      console.log(i);
      i++;
    }

Common Use Cases

  • Counting or repeating actions a set number of times.
  • Iterating over arrays, strings, or other sequences.
  • Generating sequences (e.g., numbers, patterns).

Tips for Beginners

  • Ensure the condition will eventually be false to avoid infinite loops (e.g., forgetting i++).
  • Use let for the counter to keep it scoped to the loop.
  • Test small loops with console.log to understand how they work.

This guide covers the core components and functionality of a for loop in JavaScript. For more advanced topics, like nested loops or using break and continue, feel free to explore further!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment