Skip to content

[Edit] JavaScript: .foreach() #7122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 48 additions & 17 deletions content/javascript/concepts/arrays/terms/forEach/forEach.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
---
Title: '.forEach()'
Description: 'Loops over the array, passing each item in the array into the callback function provided.'
Description: 'Loops over a given array, passing each item in the array into the callback function provided.'
Subjects:
- 'Web Development'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Arrays'
- 'Methods'
- 'Values'
- 'Variables'
CatalogContent:
- 'introduction-to-javascript'
- 'paths/front-end-engineer-career-path'
---

The `.forEach()` array method loops over the array, passing each item in the array into the callback function provided.
In JavaScript, the **`.forEach()`** [method](https://www.codecademy.com/resources/docs/javascript/methods) loops over a given array, passing each item in the array into the [callback function](https://www.codecademy.com/resources/docs/javascript/callbacks) provided. It is a higher-order function that accepts a callback function as an argument.

## Syntax

```js
array.forEach((value, index, array) => {...});
```pseudo
array.forEach(function(currentValue, index, arr), thisValue);
```

A function can be invoked with three arguments:
**Parameters:**

- `value`: The value of the array element.
- `index` (optional): The index of the array element.
- `array` (optional): The array itself.
- `index` (Optional): The index of the array element.
- `array` (Optional): The array itself.
- `thisValue` (Optional): Value to use as this when executing callback.

**Note:** Unlike a regular `for` loop, `.forEach()` method does not provide a way to terminate iteration before all elements have been passed to the function.
> **Note:** Unlike a regular `for` loop, `.forEach()` method does not provide a way to terminate iteration before all elements have been passed to the function.

## Example 1
## Example 1: Basic Usage of `.forEach()`

Logging each value in an array:
This example uses the `.forEach()` method to print each element in an array:

```js
['a', 'b', 'c'].forEach((letter) => console.log(letter));
Expand All @@ -44,29 +47,57 @@ b
c
```

## Example 2
## Example 2: Summing Elements Using `.forEach()`

Finding the sum of an array:
This example uses the `.forEach()` method to sum the elements in an array:

```js
const values = [7, 17, 34, 41, 22, 5];

let sumOfValues = 0;

values.forEach((value) => (sumOfValues += value));

console.log(sumOfValues);
// Output: 126
```

## Codebyte Example
The output would be:

```shell
126
```

## Codebyte Example: Multiplying Elements Using `.forEach()`

The following codebyte example multiplies all the values in an array and returns the product:
This codebyte example uses the `.forEach()` method to multiply the elements in an array:

```codebyte/js
```codebyte/javascript
const values = [8, 12, 21, 58, 2, 3];

let productOfValues = 1;

values.forEach((value) => (productOfValues *= value));

console.log(productOfValues);
```

## Frequently Asked Questions

### 1. What is the difference between `.map()` and `.forEach()`?

The main difference between `.map()` and `.forEach()` is that `.map()` returns a new array with transformed elements, while `.forEach()` performs operations on each element without returning anything.

Use `.map()` for data transformation and `.forEach()` for side effects like logging or DOM updates. Also, `.map()` is chainable, but `.forEach()` is not.

### 2. Is JavaScript `.forEach()` in order?

Yes, `.forEach()` executes its callback in order, from index `0` to the last element of the array. It is synchronous and does not skip elements (unless the array is modified during iteration).

### 3. Which is faster: `.map()` or `.forEach()`?

In general, `.forEach()` and `.map()` have very similar performance, but:

- `.forEach()` is usually slightly faster in most JavaScript engines.
- `.map()` creates a new array, which introduces a bit more overhead.

However, the performance difference is negligible for small to medium datasets. The key factor should be readability and intent, not raw speed.