Iterating Arrays: `for` vs. `forEach` Loops
Master the two primary ways to loop through arrays in JavaScript and learn exactly when to use each for clean, efficient code.
// Our data: An array of emojis
const fruits = [🍎, 🍌, 🍒];
The Classic `for` Loop
The traditional `for` loop is the workhorse of iteration in many languages. It works by setting up a counter (usually `i` for "index"), a condition to continue, and an incrementer. This gives you direct access to the index of each element, which is useful for more complex operations.
The Modern `forEach` Method
The `forEach` method offers a cleaner, more readable syntax. It executes a function for each element in the array, automatically passing the element itself as an argument. It abstracts away the index management, leading to more declarative and less error-prone code for simple iterations.
Key Difference: Control vs. Simplicity
The main difference lies in control flow. A `for` loop allows you to use `break` to exit the loop early or `continue` to skip an iteration. `forEach` does not support these; it will always run for every single element in the array. This makes `for` loops more flexible for search algorithms or conditional processing.
When to Use Which?
Choose a `for` loop when you need the element's index, or if you might need to stop the loop early (`break`). Choose `forEach` for its superior readability when you simply need to perform an action on every element of the array without complex control flow.
Practice Zone
Interactive Test 1: Match the Concept
Match the loop type to its primary characteristic.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build the `for` Loop
Complete the classic `for` loop syntax.
Rellena los huecos en cada casilla.
const items = ['a', 'b', 'c']; for (let i = ; i < ; i) { console.log(items[i]); }
Practice Example: Use `forEach`
Given the `prices` array, use a `forEach` loop to log each price to the console.
Arrays in Action: Beyond the Loop
`for` and `forEach` are for executing actions. But often, you want to *transform* data. JavaScript provides powerful, expressive array methods for these tasks.
1. Creating a New Array with `.map()`
The `.map()` method creates a **new array** by applying a function to each element of the original array. It's perfect for transformations, like doubling numbers or formatting data.
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
// doubled is now [2, 4, 6]
[1, 2, 3]
↓ .map()
[2, 4, 6]
2. Filtering an Array with `.filter()`
The `.filter()` method creates a **new array** containing only the elements that pass a test (a function that returns `true` or `false`). It's ideal for searching or selecting subsets of data.
const ages = [12, 18, 25];
const adults = ages.filter(age => age >= 18);
// adults is now [18, 25]
[12, 18, 25]
↓ .filter()
[18, 25]
3. Aggregating Data with `.reduce()`
The `.reduce()` method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a **single value**. It's the most powerful of the bunch, perfect for calculating sums, averages, or grouping data.
const prices = [5, 10, 15];
const total = prices.reduce((sum, p) => sum + p, 0);
// total is now 30
[5, 10, 15]
↓ .reduce()
30
Practical Takeaway: Use `forEach` when you need to *do something* (like printing to console or updating the DOM). Use `.map`, `.filter`, and `.reduce` when you need to *derive a new value or array* from the original without modifying it.
Array Iteration Glossary
- Iteration
- The process of repeating a set of instructions for each item in a collection, like an array.
- Index
- The numerical position of an element in an array, starting from 0. `array[0]` is the first element.
- `for` loop
- A control flow statement for iteration that uses a counter (`i`), a condition (`i < length`), and an incrementer (`i++`). Offers maximum control.
- `forEach()` method
- An array method that executes a provided "callback function" once for each array element. Simpler and more readable for direct iteration.
- Callback Function
- A function passed into another function as an argument, which is then invoked to perform some routine. `forEach`, `map`, and `filter` all use callbacks.
- `break` statement
- A statement that terminates a loop (like `for` or `while`) prematurely. **Does not work** in a `forEach` loop.
- `continue` statement
- A statement that skips the rest of the current iteration and proceeds to the next one in a loop. **Does not work** in a `forEach` loop.