📝

JavaScript forEach Method Overview

Jun 7, 2025

Overview

This lecture explains how the JavaScript forEach method works, how to use callback functions with it, and demonstrates practical examples for iterating over arrays.

Using forEach Method

  • The forEach method executes a function on every element of an array.
  • The callback function receives three parameters: current value (item), index, and the array itself.
  • Usually, only the item and index are used in practice.
  • You can define the callback as a separate function or as an inline arrow function.

Example: Logging Array Elements

  • Given an array [1, 2, 3, 4, 5], using forEach logs each element with its index.
  • Example output: "a of 0 is 1", "a of 1 is 2", etc.
  • The callback can be simplified to an inline arrow function for convenience.

Example: Summing Array Elements

  • Initialize a sum variable to zero.
  • Use forEach with an arrow function to add each array element to the sum.
  • Updated array values (e.g., [1,2,3,4,5,10,15,25]) are handled the same way for summing.

Example: Counting Frequency of Letters

  • Create an array of letters (e.g., ['a', 'b', 'a', 'b', 'c', 'd', 'a']).
  • Use an object to keep count of how many times each letter appears.
  • The callback checks if a property exists in the object and increments or initializes it.
  • The result is an object with letter keys and their occurrence counts.

Key Terms & Definitions

  • forEach method — An array method that calls a function on each element.
  • Callback function — A function passed as a parameter to another function (here, used with forEach).
  • Arrow function — Concise syntax for writing functions in JavaScript.

Action Items / Next Steps

  • Practice using forEach to perform different operations on arrays.
  • Experiment with defining callback functions both separately and as arrow functions inline.
  • Try implementing frequency counting for other data types or structures.