Overview
This lecture explains how the JavaScript forEach array method works, including its callback parameters and common use cases.
How forEach Works
- The
forEach method executes a given function once for each array element.
- The callback function receives three parameters: the current value, the index, and the original array.
- Usually, only the value and index are used in the callback.
Basic Usage Examples
- To log array elements, use
forEach with a callback that logs each item.
- The index parameter allows for custom messages, e.g., showing each item's index and value.
- Callback functions can be written as named functions or inline arrow functions.
Practical Applications
- Calculate the sum of array numbers by initializing a variable and adding each item within the
forEach callback.
forEach can process arrays of any length or content, such as numbers or letters.
- Count the frequency of each letter in an array by updating an object within the
forEach callback.
Example: Counting Letter Occurrences
- Create an object to store counts.
- For each letter, increment the count if it exists; otherwise, initialize it to one.
- The result is an object mapping each letter to its occurrence count.
Key Terms & Definitions
- forEach — An array method that executes a callback on each array element.
- Callback function — A function passed as an argument and called for each array element.
- Arrow function — A concise syntax for writing functions using
() => {}.
- Index — The position of the current element within the array.
Action Items / Next Steps
- Practice using
forEach to iterate through arrays and modify or analyze their elements.
- Try writing both named and inline arrow function callbacks.
- Create your own array operations using
forEach (e.g., summing numbers, counting item occurrences).