Loops in JavaScript
What Are Loops?
Loops allow you to repeat code multiple times without having to write it over and over. Think of a loop like a washing machine cycle – it repeats the same steps until the task is complete.
In programming, loops are essential for processing lists of data, running simulations, or repeating actions until a certain condition is met.
For Loops
The most common type of loop is the for loop. It has three parts: initialization, condition, and increment.
// Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
This loop will print:
1
2
3
4
5
Let's break down how it works:
let i = 1: Start with i equal to 1i <= 5: Keep looping as long as i is less than or equal to 5i++: After each loop, increase i by 1- The code inside
{ }runs each time
While Loops
A while loop repeats as long as a condition is true:
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
This produces the same output as the for loop example. Use while loops when you don't know in advance how many times you need to loop.
Looping Through Arrays
Loops are often used to process each item in an array:
let colors = ["red", "green", "blue", "yellow"];
// Loop through each color
for (let i = 0; i < colors.length; i++) {
console.log("Color: " + colors[i]);
}
This code visits each element in the array and prints it.
Nested Loops
You can put loops inside other loops. These are called nested loops:
// Print a 3x3 grid
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
console.log("Position: " + row + "," + col);
}
}
The outer loop runs 3 times, and for each of those times, the inner loop runs 3 times – resulting in 9 total iterations.
Loop Control: Break and Continue
Sometimes you need special control within loops:
breakexits the loop completelycontinueskips the rest of the current iteration and moves to the next one
// Find the first even number and stop
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) { // If i is even
console.log("Found even number: " + i);
break; // Stop the loop
}
}
// Print only odd numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) { // If i is even
continue; // Skip this iteration
}
console.log("Odd number: " + i);
}
For...Of Loops
Modern JavaScript offers a simpler way to loop through arrays:
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log("I like " + fruit);
}
This automatically loops through each element without needing an index variable.
Loops in Conway's Game of Life
Loops are essential in our Game of Life project:
- We use loops to create and initialize the grid:
// Create a 2D grid
for (let i = 0; i < cols; i++) {
grid[i] = new Array(rows);
for (let j = 0; j < rows; j++) {
grid[i][j] = 0; // Initialize all cells as dead
}
}
- We use nested loops to visit every cell in the grid:
// Process every cell
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
// Do something with grid[i][j]
}
}
- We use loops to count neighbors around a cell:
// Count live neighbors
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
// Skip the cell itself
if (i === 0 && j === 0) continue;
// Add up the neighbors
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
return sum;
}
Common Loop Patterns
Here are some frequent uses of loops:
-
Counting: Going through numbers in a range
for (let i = 0; i < 10; i++) {
console.log(i);
} -
Summing: Adding up values
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i; // Add each number to sum
}
console.log("Sum of 1-100:", sum); -
Finding: Searching for a value
let found = false;
for (let i = 0; i < items.length; i++) {
if (items[i] === "target") {
found = true;
break; // Stop looking
}
}
Loop Pitfalls to Avoid
Some common mistakes with loops:
-
Off-by-one errors: Make sure your loop starts and ends at the right indices
// Correct: for arrays, start at 0 and use < length
for (let i = 0; i < array.length; i++) { } -
Infinite loops: Always ensure your loop condition will eventually become false
// Dangerous: might never end!
while (x !== 10) {
// If x is never exactly 10, this continues forever
} -
Forgetting to update the counter: In while loops, don't forget to update your counter variable
let i = 0;
while (i < 10) {
console.log(i);
i++; // Important! Without this, the loop never ends
}
Summary
- Loops repeat code until a condition is met
forloops are used when you know how many iterations you needwhileloops are used when the number of iterations is uncertain- Nested loops put one loop inside another
breakexits the loop,continueskips to the next iteration- Loops are essential for working with arrays and grids