Answers for "map vs for each"

20

difference between foreach and map in js

forEach() just loop through the elements. It's throws 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 main array

Example:

   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()
Posted by: Guest on April-23-2020
2

map vs for each

chars = ['Hello' , 'world!!!'] ;
var retVal = chars.forEach(function(word){
  console.log("Saving to db: " + word) 
})
console.log(retVal) //undefined

chars = ['Hello' , 'world!!!'] ;
var lengths = chars.map(function(word){
  return word.length
}) 
console.log(lengths) //[5,8]
Posted by: Guest on July-05-2021

Code answers related to "TypeScript"

Browse Popular Code Answers by Language