Back to Blog
Lesson 13 of the JavaScript: From Zero to Interactive Web Pages course
JavaScriptJuly 31, 20264 min read

Introduction to Loops: Automate Iteration in JavaScript

Stop manual indexing. Learn how to write a standard for loop to iterate over arrays and process your to-do items automatically in this JavaScript lesson.

javascriptloopsprogrammingiterationweb-developmentbeginner-guide
Detailed view of programming code in a dark theme on a computer screen.

Previously in this course, we learned how to store multiple items in an array in Introduction to Arrays: Managing Collections in JavaScript and how to manage that data using Objects and Data Grouping. While those lessons taught us how to store and access individual items by their index, real-world applications rarely know exactly how many items they need to process.

In this lesson, we introduce loops, the mechanism that allows your code to repeat an action for every element in a list without you having to write the same line of code over and over.

Understanding Iteration from First Principles

In programming, iteration is the process of repeating a sequence of instructions until a specific condition is met. Think of it like a chef checking every ingredient in a pantry: instead of saying "Check flour, then check sugar, then check salt," the chef says "For every item in the pantry, check the expiration date."

A for loop is the most common tool for this task in JavaScript. It creates a controlled environment where you can increment a counter, compare it to the length of your data, and execute code for each "step."

The Anatomy of a for loop

A standard for loop consists of three distinct parts inside the parentheses:

  1. Initialization: Where you define your starting point (usually let i = 0).
  2. Condition: The rule that keeps the loop running (e.g., i < array.length).
  3. Final Expression: What happens after each loop (usually i++ to move to the next index).
JAVASCRIPT
// The syntax structure
for (let i = 0; i < 5; i++) {
  console.log("Current index is: " + i);
}

Iterating Over Your To-Do List

A detailed project timeline featuring design and development phases on a whiteboard with sticky notes.

In our project, we have an array of tasks. Instead of logging them one by one, we can use the array's .length property to ensure we touch every single task, regardless of whether the list has three items or three hundred.

Here is how you apply a for loop to an array:

JAVASCRIPT
const todoList = ["Buy milk", "Clean the kitchen", "Finish coding lesson"];

// We use todoList.length to determine when the loop should stop
for (let i = 0; i < todoList.length; i++) {
  console.log("Task " + (i + 1) + ": " + todoList[i]);
}

When this code runs, JavaScript sets i to 0, logs the first item, increments i to 1, logs the second, and continues until i is no longer less than the array length.

Why use i?

The variable i is a convention standing for "index." Since arrays are zero-indexed, starting at 0 allows us to access the first element perfectly using array[i].

Hands-On Exercise

Open your browser's console or your project's .js file. Create an array called myGoals containing at least four strings representing your learning goals for this week.

Write a for loop that prints each goal to the console in the format: "Goal [Number]: [Goal Name]". Ensure you use the loop variable to dynamically calculate the number.

Common Pitfalls to Avoid

Text cubes spelling 'DON'T' on a clean white background, ideal for concepts of caution or prohibition.

As you begin writing loops, keep an eye on these two common mistakes that can freeze your browser:

  • The Infinite Loop: If you forget to increment your counter (e.g., you write i instead of i++) or your condition is always true (like i < 10 but i is initialized as 0 and never changes), the loop will run forever. This will crash your browser tab.
  • Off-by-One Errors: Remember that array indices start at 0. If your array has 3 items, the indices are 0, 1, 2. If you use i <= array.length as your condition, the loop will attempt to access array[3], which is undefined. Always use the strict "less than" (<) operator when comparing against .length.

FAQ

Q: Can I use a for loop for things other than arrays? A: Yes, you can use them for any numeric range, but they are most powerful when paired with data structures like arrays or objects.

Q: Is there a limit to how many times a loop can run? A: Technically no, but practically, loops that run millions of times can make your page unresponsive. Keep your logic inside loops lean.

Q: Does it have to be named i? A: No, you can name it index, counter, or x. However, i is the industry-standard convention that other developers will expect to see.

Recap

Team members presenting a project in a modern office setting with a focus on collaboration.

You have now moved from manually handling individual data points to automating repetitive tasks. By using the for loop, you've learned to:

  1. Define the start, condition, and increment of a loop.
  2. Use the array's .length property to safely iterate through collections.
  3. Access specific elements dynamically using the loop index i.

This skill is essential for the next phase of our project: rendering your to-do items directly into the HTML document.

Up next: We will explore While Loops and Conditionals to handle scenarios where we might not know exactly how many times a loop needs to run.

Similar Posts