Skip to content Skip to sidebar Skip to footer

Reactjs Map Works But Foreach Doesn't

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

Solution 1:

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><TodoItemid={item.id}key={item.id}text={item.text} /></li>
                     ))

  return(
     <ul>{items}</ul>
  );
}

Solution 2:

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]

Solution 3:

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.

Solution 4:

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.

Solution 5:

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 undefinedvar mapNum = numbers.map(function(number) {
  return number
})
console.log(mapNum)
//output [2,3,5,7]//map() is faster than forEach()

Post a Comment for "Reactjs Map Works But Foreach Doesn't"