Recommended resources
The freely available resources this lesson will direct you to.
Hello! Welcome back to your front-end programming course.
In our last lesson, we learned how to create and manage ordered lists of data using JavaScript arrays. We practiced adding, removing, and accessing individual elements, much like managing a playlist or the steps in a checkout flow.
Today, we'll build directly on that knowledge. It's one thing to have data in an array, but it's another to be able to do something with every single item in that list. This is a fundamental task in UI development, whether you're displaying a list of products, rendering a feed of user comments, or creating a navigation menu from a list of page names.
This lesson addresses the learning outcome: Use loops such as for and while to iterate over data arrays. We will focus on these two foundational looping structures to systematically process each element in an array.
1. The Concept of Iteration
Iteration simply means repeating a process for each item in a collection. Imagine you have a stack of design mockups and your task is to review each one and leave a comment. You would pick one up, review it, comment, and then move to the next, repeating the process until the stack is empty.
In programming, loops are the mechanism that automates this repetition. We'll start with the most traditional and common loop for this purpose: the for loop.
2. The Classic for Loop
The for loop is perfect for when you know exactly how many times you want to repeat an action—for example, once for each element in an array.
Its syntax might look a bit dense at first, but it's made of three distinct parts that are easy to understand when broken down.
for (initialization; condition; final-expression)
- Initialization:
let i = 0;— A counter variable is created and set to0. We typically useifor "index". This runs only once at the very beginning. - Condition:
i < array.length;— Before each repetition (iteration), this condition is checked. If it's true, the code inside the loop runs. If it's false, the loop stops. We loop as long as our counteriis less than the total number of items in the array. - Final Expression:
i++— This runs at the end of each iteration. It increments our counter (i++is shorthand fori = i + 1), moving us to the next index.
Let's see this in action.
This video from Coding Journey provides a clear, step-by-step explanation of the for loop syntax and how to apply it to arrays.
Please watch from 00:32 to 05:54. The video will cover: The basic syntax and the three parts of a for loop. How to use a for loop to iterate through an array, accessing both the index (i) and the value (myArray[i]).
As the video demonstrates, this structure allows us to visit each element of an array by its index.
Here's a practical example. Imagine you have an array of color codes for a design system palette. You can use a for loop to print each one.
const colorPalette = ["#FF5733", "#33FF57", "#3357FF", "#F333FF"];
console.log("Design System Colors:");
for (let i = 0; i < colorPalette.length; i++) {
// Access the element at the current index 'i'
const color = colorPalette[i];
console.log(`Color at index ${i}: ${color}`);
}
Output:
Design System Colors:
Color at index 0: #FF5733
Color at index 1: #33FF57
Color at index 2: #3357FF
Color at index 3: #F333FF
3. The while Loop
Another fundamental loop is the while loop. Instead of being structured around a known number of iterations, a while loop simply runs while a certain condition is true.
The setup is slightly different from a for loop. You must manage the counter variable yourself:
- Initialize the counter before the loop starts.
- Set the condition in the
whilestatement. - Increment the counter inside the loop's code block.
Let's continue with the same video to understand the while loop and see how it compares to the for loop for iterating over an array.
Watch from 06:58 to 12:50. Focus on: The syntax of the while loop. The importance of incrementing your counter variable to avoid an infinite loop. The general guidance on when to choose a for loop versus a while loop.
Here is the same color palette example, but using a while loop:
const colorPalette = ["#FF5733", "#33FF57", "#3357FF", "#F333FF"];
console.log("Design System Colors (using while):");
// 1. Initialize the counter
let i = 0;
// 2. Set the condition
while (i < colorPalette.length) {
const color = colorPalette[i];
console.log(`Color at index ${i}: ${color}`);
// 3. Increment the counter
i++;
}
The output is identical. For iterating over an array, the for loop is generally more common because it bundles the initialization, condition, and increment logic neatly in one line.
A Crucial Warning: Infinite Loops
The biggest risk with while loops is accidentally creating an infinite loop. If you forget to increment the counter (i++), the condition (i < colorPalette.length) will always be true, and your loop will run forever, crashing the browser tab.
This article from Per Scholas provides a concise explanation of infinite loops and how to avoid them. It's a critical concept for writing stable code.
Read the section titled 'Infinite Loops'. It starts after the section on do...while loops and ends just before the 'Hands-On' activity. Pay attention to the examples of what causes an infinite loop in both while and for loops.
Always double-check that the loop's condition will eventually become false!
4. Your Turn: Displaying a Product List
Now it's time to put this into practice. Let's say you're working on an e-commerce site and you've received a list of product names in an array. Your task is to iterate through this list and display each product.
Your Task:
- In your code editor, create an array called
productscontaining the following items:"Laptop","Smartphone","Headphones","Tablet". - Using a
forloop, iterate through theproductsarray. For each product, log a message to the console like"Product found: Laptop". - Using a
whileloop, perform the exact same task. This will help you contrast the syntax and structure of the two loops.
Take your time to write the code for both tasks. You can check your work against the solution below.
Click here to see the solution
const products = ["Laptop", "Smartphone", "Headphones", "Tablet"];
// Task 1: Using a 'for' loop
console.log("--- Using a for loop ---");
for (let i = 0; i < products.length; i++) {
console.log(`Product found: ${products[i]}`);
}
// Task 2: Using a 'while' loop
console.log("\n--- Using a while loop ---");
let j = 0; // Using 'j' to avoid reusing 'i' in the same scope
while (j < products.length) {
console.log(`Product found: ${products[j]}`);
j++;
}
A Note on Modern Loops
While for and while are the foundational loops, modern JavaScript offers more concise ways to iterate over arrays, like the for...of loop. It handles the counter and condition for you automatically.
// Using a for...of loop
for (const product of products) {
console.log(`Product found: ${product}`);
}
This is often more readable when you just need the value of each item and not the index. We'll encounter this and other modern iteration methods like forEach() and map() later in the course. For now, mastering the classic for loop is the most important step, as it gives you the most control and understanding of the underlying mechanics.
Conclusion
Great job! You've learned how to automate repetitive tasks by iterating through arrays. This is the bridge between having raw data and being able to present it or work with it in a user interface.
Key Takeaways:
- Loops are used to execute a block of code repeatedly.
- The
forloop is ideal for iterating a known number of times, like for every element in an array. Its syntax isfor (initialization; condition; final-expression). - The
whileloop runs as long as a specified condition is true. You must initialize and increment your own counter. - Forgetting to change the condition variable inside a
whileloop can lead to an infinite loop.
In this lesson, we iterated through data and printed it to the console. In our next lesson, "Select DOM elements using querySelector and querySelectorAll methods", we'll take the crucial next step: learning how to select elements on an actual webpage so we can start dynamically adding our array content to the UI.