Enhance your JS Skill by using the correct array method
Tags: javascript, webdev, beginners, codenewbie
Published: 2021-11-05 10:51:19

I saw a lot of junior developper using forEach when they need to handle array.

I will show you and help you to over-abuse of `forEach` by using the correct array methods depending on the current context!

### forEach

_When to use?_  

As I said before, you don't need to over-abuse of `forEach`. In some case forEach is a very good method.

If you need to iterate an array in order to make a specific action (for example console log each item).

You **shouldn't use forEach** every time you need to **fill** a new array (before doing this, check if you can use other methods)

👇

```javascript
const items = [1, 2, 3, 4, 5]

items.forEach(item => console.log(item))
```

`forEach` **DOESN'T** return any value !!

```javascript
// 
// ...
const toto = items.forEach(item => console.log(item))
toto // undefined
```

### filter

_When to use?_  

As named, it allow us to filter some value in your array depending on your condition.

Example 👇

For example if you want to remove odd number

_❌ With forEach_ 

```javascript
const items = [1, 2, 3, 4]
const evenValue = []
items.forEach(item => {
   if (item % 2 == 0) {
      evenValue.push(item)
   }
})
```

_✅ With filter_ 

```javascript
const items = [1, 2, 3, 4]

const evenValue = items.filter(currentValue => {
   return currentValue % 2 == 0
})
```

💡 When you are using `filter` you **should return a boolean** (the condition of filter) in each iteration. (otherwise JS Engine will coerce the returned value into boolean!)

### map

_When to use?_ 

When you need to transform items from array to another array!

Example 👇

For example if you want to multiply all value in an array by 2.

_❌ With forEach_ 

```javascript
const items = [1, 2, 3, 4]
const result = []
items.forEach(item => {
   result.push(item * 2)
})
```

_✅ With map_

```javascript
const items = [1, 2, 3, 4]
const result = items.map(item => {
   return item * 2
})
```

💡 When you are using `map` you **need to return an item** (transformed item) in each iteration.

### reduce

_When to use?_  

When you need to get a **single value** from an array. This 'single value' can be an array.

Example 👇

For example if you want to sum all number in array.

_❌ With forEach_ 

```javascript
const items = [1, 2, 3, 4]
let accumulator = 0

items.forEach(item => {
   accumulator += item
})
```

_✅ With reduce_

```javascript
const items = [1, 2, 3, 4]

const sum = items.reduce((accumulator, currentValue) => {
   return accumulator += currentValue
}, 0)
```

💡 When you are using `reduce` you **need to return the accumulator** (value that is returned by the reduce method) in each iteration and you should also **init this accumulator** (in the example above we init the accumulator to `0`)!

### find

_When to use?_

When you need to find an item that fit a condition and you are using this item after.

```javascript
const items = [1, 2, 3, 4]

const item = items.find(item => item === 3)

// ...

// Use item afterwards
```

### some

_When to use?_ 

If you need to check if one of you item match a condition (like `find`) but you don't need to use the item afterward.

Example 👇

For example if you want to check if you array has the number 2.

Using `find` is bad if you **don't use item afterward**, or you just use item for checking if the value is `undefined` or not (to know if the condition has matched)

_❌ With find_ 

```javascript
const items = [1, 2, 3, 4]
const item = items.find(item => item === 2)
if (item !== undefined) {
   // ...
}
```

_✅ With some_ 

```javascript
const items = [1, 2, 3, 4]
const hasNumber2 = items.some(item => item === 2)
if (hasNumber2) {
   ...
}
```

💡 `some` return boolean if at least **one item matched your condition**


### every

_When to use?_ 

`every` is similar to `some`, it will check if **ALL of your items** match your condition. Instead of `some` that will return true if only one item match the condition, `every` will return true only if all items match the condition!

### TLDR; 

As you can see you can use a lot of array methods depending on the context, so you can avoid to over-abuse of `forEach`!

It's also a good point to use methods **depending on the current context** for other developers that will read you code (for example if I see filter I know that we need to filter a value from this array)

A good point that I didn't show above, it's about the fact that you can **combining array methods** (except `forEach` since forEach doesn't return value).

So you can make this 👇

You need to filter odd value from array and multiply event number by 2.

```javascript
const items = [1, 2, 3, 4]

const result = items.filter(item => item % 2 == 0 ).map(item => item * 2)
```

---

I hope you like this reading!

🎁 You can get my new book `Underrated skills in javascript, make the difference` for FREE if you follow me on [Twitter](https://twitter.com/code__oz) and send message to me 😁 and **SAVE 19$** 💵💵

Or get it [HERE](https://codeoz.gumroad.com/l/RXLYp) 

🇫🇷🥖 For french developper you can check my [YoutubeChannel](https://www.youtube.com/channel/UCC675U1ZUPFASsK9-FjawtA)

🎁 [MY NEWSLETTER](https://www.getrevue.co/profile/code__oz)

☕️ You can [SUPPORT MY WORKS](https://www.buymeacoffee.com/CodeoZ) 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : [https://twitter.com/code__oz](https://twitter.com/code__oz)

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!