for vs forEach vs map

sakethkowtha

sakethk

Posted on April 3, 2022

for vs forEach vs map

Hello ๐Ÿ‘‹ ,

Javascript new bees may confuse on for, forEach and map. In this article i will explain difference between for, forEach and map.

for

For is loop it is standard loop we can find in many programming languages.

Here is the syntax

for(;;)
Enter fullscreen mode Exit fullscreen mode

We have a control over iterations in for loop. We can continue iterations or break conditionally .

forEach and map

forEach and map both are array methods. We can only use those on array.

map will accept call-back function and runs that function on each and every element in array and returns result array.

const list = [1,2,3,4]
const inc = x => x + 1
const result = list.map(inc) 
result // [2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

like map, forEach also accept call-back function and runs that function on each and every element in array and it will not return any thing like map.

const list = [1,2,3,4]

const inc = x => x + 1
const printIncrementedValue = x => console.log(x + 1)

const result = list.forEach(inc) 
result //undefined
list.forEach(printIncrementedValue) // 2,3,4,5
list.map(printIncrementedValue) // prints 2,3,4,5 and returns [undefined, undefined, undefined, undefined]
Enter fullscreen mode Exit fullscreen mode

How to choose ?

If you want to transform a list or expecting a result then you can pick map

const strToDate = str => new Date(str)
const list = [1648989124036, 1648989124037, 1648989124038]
list.map(strToDate) // You will get date objects
Enter fullscreen mode Exit fullscreen mode

If you are not expecting any return and you just want to perform a function on array then forEach is good fit

const list = [1648989124036, 1648989124037, 1648989124038]
list.forEach(console.log) // prints array
Enter fullscreen mode Exit fullscreen mode

If you want control over array iterations or if you want iteration without array you have to pick 'for'

One best example is finding an element in an array. map will not fit for this case and forEach will work because we don't have control over that so we cannot break the iteration after finding an element. But with for loop we can break once we find it.

const list = [1,2,3,4]

const find = (arr, ele) => {
 for(let i = 0; i < arr.length; i++){
  if(arr[i] === ele)
   return true
 }
 return false
}
find(list, 2) // Iteration will stop once element is found and returns true.
Enter fullscreen mode Exit fullscreen mode

Cheers,
Happy coding!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
sakethkowtha
sakethk

Posted on April 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About