Skip to content

Commit

Permalink
Add forEach vs. map section to JS questions (yangshun#5)
Browse files Browse the repository at this point in the history
* Add forEach vs. map section to JS questions

* Update README.md
  • Loading branch information
DanLindeman authored and yangshun committed Feb 11, 2018
1 parent be31409 commit 382e657
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -765,9 +765,44 @@ A closure is the combination of a function and the lexical environment within wh
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
* https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36

### Can you describe the main difference between a `forEach` loop and a `.map()` loop and why you would pick one versus the other?
### Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other?

TODO
To understand the differences between the two, let's look at what each function does.

**`forEach`**

- Iterates through the elements in an array.
- Executes a callback for each element.
- Does not return a value.

```js
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
// Do something with num and/or index.
});

// doubled = undefined
```

**`map`**

- Iterates through the elements in an array.
- "Maps" each element to a new element by calling the function on each element, creating a new array as a result.

```js
const a = [1, 2, 3];
const doubled = a.map(num => {
return num * 2;
});

// doubled = [2, 4, 6]
```

The main difference between `.forEach` and `.map()` is that `.map()` returns a new array. If you need the result, but do not wish to mutate the original array, `.map()` is the clear choice. If you simply need to iterate over an array, `forEach` is a fine choice.

###### References

* https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

### What's a typical use case for anonymous functions?

Expand Down

0 comments on commit 382e657

Please sign in to comment.