0

Why on the lower example in createGrid i have to use array.map method when forEach is almost the same with

import React from 'react';
import Square from './Square.js'

const Board = ({squaresList}) => {
    const createGrid = squaresList.map((item, i) => { // squareList.forEach not working here - not returning <Square/> components.
        return(
            <Square key={i}id={item.id}/>
        )
    })
        return(
            <div className='game-board-container'>
                <div className='squares-container'>
                    {createGrid}
                </div>
            </div>
        )
}

export default Board;
kind user
  • 40,029
  • 7
  • 67
  • 77
Mateusz W
  • 51
  • 1
  • 7
  • See the linked duplicate and the notice the return value of `forEach` [is `undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) – Brian Thompson Oct 28 '20 at 16:04

3 Answers3

1

map creates a new array whereas forEach just loops through the array. In this case, we want createGrid to be an array of Square components. If you use forEach then, createGrid will be undefined.

According to MDN

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

whereas in forEach

The forEach() method executes a provided function once for each array element.

illiteratewriter
  • 4,155
  • 1
  • 23
  • 44
1

Becuase Array.prototype.map() returns a new Array and Array.prototype.forEach() returns undefined.

The choice between map() and forEach() will depend on your use case. If you plan to change, alternate, or use the data, you should pick map(), because it returns a new array with the transformed data.

But, if you won't need the returned array, don't use map() - instead use forEach() or even a for loop.

Check out the article from FreeCodeCamp. They wrote a nice article about the differences between these two methods.

Mejan
  • 918
  • 13
  • 18
0

forEach() method doesn’t actually return anything (undefined). It simply calls a provided function on each element in your array. This callback is allowed to mutate the calling array.

map() method will also call a provided function on every element in the array. The difference is that map() utilizes return values and actually returns a new Array of the same size.

hmamun
  • 154
  • 1
  • 15