Avoiding Pitfalls in Array Methods (forEach, filter, and map)

Modified on Wed, 31 Jul at 10:04 AM

Method

Example Array = [1, 2, 3, 4, 5] 

N = 5

Return value

Resulting Array

forEach

Array.forEach(item => console.log(item * 2))

undefined

  • Undefined

  • Output for example array:  undefined

filter

Array.filter(item => item > N / 2)

array

  • New array with <= 5 elements

  • Output for example array: [3,4,5]

map

Array.map(item => item * N)

array

  • New array with 5 elements

  • Output for example array: 

  • [5, 10, 15, 20, 25]



Table of Contents

  1. forEach

    1. Trying to return a value

    2. Using the array name for the element

  2. filter

    1. Using it to transform elements


forEach

Trying to return a value


Can you figure out the issue in the below code:



Issue: 

forEach doesn't return a new array. It always returns undefined.



Fixed Code: 

Instead of returning directly from the loop, create a new array and push the values to the new array.



Using the array name for the element


Can you figure out the issue in the below code:



Issue: 

Using the array name (numbers) as the parameter name in the callback function shadows the original array and can lead to unexpected behaviour.



Fixed Code:

Use a different variable name for the variable used for the element



filter

Using it to transform elements


Can you figure out the issue in the below code:



Issue: 

filter is used to select elements, not transform them. It keeps elements for which the callback returns true.



Fixed Code:

To transform elements we should use a map.



Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article