Array Iteration: for, forEach, map, filter, reduce
Iterating over arrays is a fundamental task in programming: you often need to process each item, transform a list, select specific items, or calculate a single value from a collection. JavaScript provides several ways to iterate over arrays, from traditional loops to powerful higher-order functions that enable more expressive and functional programming styles.
This lesson explores the common iteration methods, focusing on when and how to use each effectively.
1. Traditional for Loop & for...of Loop
These are basic looping constructs that give you fine-grained control over the iteration process.
a) for loop (Traditional)
- Pros: Complete control over iteration (start, end, step), allows
breakandcontinuestatements. - Cons: More verbose, requires managing an index.
const items = ['pen', 'book', 'paper'];
for (let i = 0; i < items.length; i++) {
console.log(`Index ${i}: ${items[i]}`);
}
b) for...of loop (ES6+)
- Pros: More concise and readable than
forloop, directly iterates over values, allowsbreakandcontinue. - Cons: No direct access to index without
entries().
const numbers = [10, 20, 30];
for (const num of numbers) {
console.log(num);
}
// To get index with for...of:
for (const [index, num] of numbers.entries()) {
console.log(`Item at index ${index}: ${num}`);
}
2. forEach(): Executing a Function for Each Element
The forEach() method executes a provided function once for each array element. It's primarily used for performing side effects (like logging to console, updating UI, etc.) rather than transforming the array.
- Syntax:
array.forEach(callback(currentValue, index, array), thisArg) - Returns:
undefined. It does not create a new array.
3. map(): Transforming Elements
The map() method creates a new array by calling a provided function on every element in the calling array. It's perfect for when you want to transform each item into a new form without modifying the original array.
- Syntax:
array.map(callback(currentValue, index, array), thisArg) - Returns: A new array with the results of calling the provided function on every element. The new array will always have the same length as the original.
4. filter(): Selecting Elements
The filter() method creates a new array containing all elements for which the provided callback function returns true. It's perfect for when you want to select a subset of items from an array.
- Syntax:
array.filter(callback(currentValue, index, array), thisArg) - Returns: A new array containing the elements that passed the test. If no elements pass the test, an empty array is returned.
5. reduce(): Accumulating a Single Value
The reduce() method executes a reducer function (provided by you) on each element of the array, resulting in a single output value. It's incredibly versatile and can be used for tasks like summing numbers, flattening arrays, counting instances, or building objects from arrays.
-
Syntax:
array.reduce(callback(accumulator, currentValue, index, array), initialValue) -
accumulator: The value resulting from the previous call tocallbackFn. It's the accumulated value. -
currentValue: The current element being processed in the array. -
initialValue(Optional): A value to use as the first argument to the first call of thecallbackFn.- If
initialValueis provided,accumulatorstarts withinitialValueandcurrentValuestarts with the first array element. - If
initialValueis not provided,accumulatorstarts with the first array element, andcurrentValuestarts with the second array element.
- If
-
Returns: The single accumulated value.
6. Choosing the Right Method
-
for/for...ofloops:- When you need to break or continue the loop.
- When performance is absolutely critical (though higher-order functions are often optimized).
- When iterating over non-array iterables (like DOM NodeLists without conversion).
-
forEach():- When you want to perform an action for each element and do not need a new array returned.
- E.g., logging, updating the DOM, sending data to an API.
-
map():- When you want to transform each element of an array into a new form and get a new array of the same length.
- E.g., squaring numbers, extracting specific properties, formatting data.
-
filter():- When you want to select a subset of elements from an array based on a condition and get a new array containing only those elements.
- E.g., getting active users, finding numbers above a threshold.
-
reduce():- When you want to accumulate a single value from an array.
- E.g., summing, counting, averaging, flattening, grouping data.
Exercise: Array Iteration Mastery
Apply your knowledge of array iteration methods to solve the following problems.
التالي · الدرس 28 من 61
Common methods: find, some, every, sort, slice
قراءة 6 دقيقة
أنهيت 27 من 61 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

