Reactjs map works but forEach doesn't
Asked Answered
C

6

40

I'm struggling to understand the difference between forEach and map. In the following render function if the 'forEach' is replaced with 'map' it works. I don't understand why it doesn't work with the 'forEach'. Both {item.id} and {item.text} are present with both methods. So, why are the props for 'TodoItem' not being set when using 'forEach' ?

render() {    
  return(

     <ul>
        {this.props.items.forEach(function(item) {

           return (
              <TodoItem id={item.id} text={item.text} />)
        })} 
     </ul>
  );
}

So if 'forEach' doesn't return anything how come this doesn't work either:

render() {    
  return(

     <ul>
        {this.props.items.forEach(function(item) {               

              <TodoItem id={item.id} text={item.text} />
        })} 
     </ul>
  );
}
Cranky answered 22/11, 2017 at 19:26 Comment(3)
Map returns new array of modified elements and forEach just iterates through array and doesn't return anything.History
Use map instead forEachLeptosome
"Use map instead forEach" that doesn't answer the question, however. WHY doesn't it work.Quickstep
D
45

The map function returns an array of items and forEach just loop over them. To make this code work use :

render() {    
  const items = [];
  this.props.items
    .forEach(item => items.push(
                       <li>
                          <TodoItem id={item.id} key={item.id} text={item.text} />
                       </li>
                     ))

  return(
     <ul>{items}</ul>
  );
}
Deft answered 22/11, 2017 at 19:31 Comment(0)
F
13

Try this simple example for understand why forEach doesn't work in this context:

[1,2,3].forEach((n)=> n); => returns undefined

[1,2,3].map((n)=> n); => returns [1,2,3]
Fabyola answered 22/11, 2017 at 19:31 Comment(1)
I want to display items in the UI, can I use forEach for that?Loaiasis
S
6

As @Nenad Vracar mentioned map will actually return stuff. If you wanted to do somethings to another array, object or piece of code you could use forEach. But since you want to return something that ends up being shown on the DOM. Use map.

Also, don't forget to return whatever you're mapping. It's a common mistake because you don't need to use the return for forEach.

Sethrida answered 22/11, 2017 at 19:33 Comment(0)
H
3

Basically map returns an array while forEach returns nothing,

in jsx/react context you need to return a list of components/node-tags that the parser will transform in nodes both in the real and virtual dom;

working by side-effect like forEach does you won't have anything to parse.

Hostler answered 22/11, 2017 at 19:31 Comment(0)
A
2

forEach() just loop through the elements. It's throwing away return values and always returns undefined. The result of this method does not give us an output.

map() loop through the elements allocates memory and stores return values by iterating the main array.

var numbers = [2, 3, 5, 7];

var forEachNum = numbers.forEach(function(number) {
  return number
})
console.log(forEachNum)
//output undefined

var mapNum = numbers.map(function(number) {
  return number
})
console.log(mapNum)
//output [2,3,5,7]

//map() is faster than forEach()
Alcorn answered 1/7, 2021 at 15:2 Comment(0)
M
0

Map returns a new Array, while ForEach returns undefined.

Here are some differences between the two methods.

Map allocates memory and stores return values, while forEach throws away return values and always returns undefined.

Map is chainable, but forEach isn't. This means that you can use other methods after map, but not after forEach.

Map is used to transform the elements of an array, while forEach is used to loop through the elements of an array.

Map returns an array of values, while forEach returns undefined.

Hopefully this helps!

Multifold answered 31/8, 2023 at 0:28 Comment(1)
hes not trying to transform elements of an array, hes trying to loop through them. So by your logic he should use ForEachCeraceous

© 2022 - 2024 — McMap. All rights reserved.