JavaScript Array forEach() method
The forEach()
method in JavaScript is used to execute a provided callback function once for each element in an array. This method is a part of the Array prototype and provides a convenient way to iterate over array elements without the need for a traditional for
loop.
Syntax:
callback
: A function that is executed for each element in the array. It can accept three parameters:currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayforEach()
was called upon.
thisArg
(optional): A value to use asthis
when executing the callback function.
Return Value:
- Undefined: The
forEach()
method returnsundefined
. It does not create a new array or return any values.
Key Points:
- Iterates over each element: The
forEach()
method calls the provided function once for each element in the array. - Modifies original array: It does not modify the original array unless explicitly done within the callback.
- Cannot be broken: Unlike traditional loops, you cannot use
break
orreturn
to stop the iteration. To exit early, you'll need to use a different loop construct.
Example 1: Basic usage
Example 2: Using index and array parameters
Example 3: Using an arrow function
Example 4: Modifying elements within the callback
Example 5: Using thisArg
Summary:
forEach()
is a convenient method for iterating over elements in an array, allowing you to apply a function to each element.- It provides access to the current element, its index, and the original array if needed.
- Since
forEach()
returnsundefined
, it is primarily used for executing side effects, like logging or modifying data, rather than for generating new arrays or collecting results.