Skip to content
This repository was archived by the owner on Jul 20, 2023. It is now read-only.

Add forEach snippet #125

Open
wants to merge 1 commit into
base: master
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
29 changes: 28 additions & 1 deletion source/snippets/javascript/index.md
Original file line number Diff line number Diff line change
@@ -87,7 +87,7 @@ function test(){

## Arrays

### find, map, filter, and reduce
### find, map, forEach, filter, and reduce
All of these array methods provide a declarative programming alternative to writing a loop. Each performs some block of code, given in a callback function, to some or all elements of an array.

Find() and filter() are used to select values from an array that meet some condition.
@@ -160,6 +160,33 @@ const double = original.map(val => val * 2);
console.log(double); // [2, 4, 6, 8]
```

### Using the forEach() method

[Array.prototype.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) is a built in JavaScript function that applies some function call to every element of an array.

It does this by running a callback function on each element in the array, without modifying the original array or returning a new one.

**forEach doesn't modify the original array and returns nothing, but keep in mind, that if you pass array of objects and modify them, than the objects in the original array will also be modified.**

#### When to use forEach()
When you want to apply some function on all elements of an array, but you don't need the new values.

#### Example: logging data from array
This is how you would use forEach() to log all data stored in array.

##### Code
```javascript
const heroes = ['Gandalf', 'Legolas', 'Aragorn', 'Gimly'];

data.forEach(partyMember => console.log(partyMember));
// Gandalf
// Legolas
// Aragorn
// Gimly

```


#### Using the reduce() method

Just like map(), [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other, accumulating the result.