I know that there were a lot of topics like this. And I know the basics: .forEach()
operates on original array and .map()
on the new one.
I
╓════════════════╥═════════════════════════════════════╥═══════════════════════════════════════╕
║ ║ foreach ║ map ║
╠════════════════╫═════════════════════════════════════╫═══════════════════════════════════════╢
║ Functionality ║ Performs given operation on each ║ Performs given "transformation" on ║
║ ║ element of the array ║ "copy" of each element ║
╠————————————————╫—————————————————————————————————————╫———————————————————————————————————————╢
║ Return value ║ Returns undefined ║ Returns new array with tranformed ║
║ ║ ║ elements leaving back original array ║
║ ║ ║ unchanged ║
╠————————————————╫—————————————————————————————————————╫———————————————————————————————————————╢
║ Preferrable ║ Performing non—transformation like ║ Obtaining array containing output of ║
║ usage scenario ║ processing on each element. ║ some processing done on each element ║
║ and example ║ ║ of the array. ║
║ ║ For example, saving all elements in ║ ║
║ ║ the database ║ For example, obtaining array of ║
║ ║ ║ lengths of each string in the ║
║ ║ ║ array ║
╙════════════════╨═════════════════════════════════════╨═══════════════════════════════════════╜