Learn
Iterators
The .forEach() Method
The .forEach()
method is a higher-order function that takes a callback function as its argument. It allows us to loop through each element in an array and perform a specific action. This method is commonly used when we want to perform a task on each item in an array without the need for a separate loop.
Syntax
The syntax for the .forEach()
method is as follows:
array
: The array that the.forEach()
method is being applied to.callbackFunction
: The function to be executed on each element of the array.currentValue
: The value of the current element being processed.index
(optional): The index of the current element being processed.array
(optional): The array that the.forEach()
method is being applied to.
Using the .forEach() Method
Let's see how we can use the .forEach()
method in practical examples:
Example 1: Printing each element in an array
Example 2: Manipulating each element in an array
Benefits of the .forEach() Method
- Simplicity: The
.forEach()
method offers a concise and readable way to iterate over arrays. - Performance: The
.forEach()
method is optimized for performance and often outperforms traditional for loops. - Closures: The callback function used in
.forEach()
allows for the use of closures, providing scope for variables within the loop.
Instructions
In the provided code, there is a numbers
array containing some numbers. Your task is to use the .forEach()
method to iterate over each number in the array and console.log it.
Replace the comment (// TODO: Use the .forEach() method to console.log each number in the array
) with your solution.
Sign up to start coding
Already have an account?
Sign In