forEach vs Map…the slight difference

Hello again ! My last couple of blogs have been about algorithms and what I’ve learned working with algorithms is how important it is to understand the fundamentals of a programming language. Often times when I look at solutions and it make sense to me but I also like to go over what each syntax does literally. Last week while going through technical questions that are asked during interviews, on of them was what is the difference between the forEach and map methods. I’ve used map more often than forEach but I’ve used it but thinking about the question I thought do I really know difference? Of course I didn’t, so blog about it!

forEach():

  • An array method.
  • Takes a function as in input.
  • When called on an array, Javascript takes the array items one by one and calls that function each of those items.
  • Javascript also passes the index of the items and the original array when the function for each item.
  • Range is fixed before the first iteration. Appending a new element to the array after the first iteration, it will not run for the newly added element.
  • If an item gets deleted from the array, the forEach function will skip over that deleted element at that index. Whereas a for loop will execute over all indexes whether it is deleted or not.
  • The function executes for each item and undefined is ALWAYS returned.

map():

  • Also an array method.
  • Also executes on every item in the array.
  • Returns a new array that consist of values, forEach does not.
  • Also ranged is fixed but if an element is deleted from the array the return value in the array will be undefined at that index, unlike a forEach which will skip over a deleted index.
  • A new array will ALWAYS be returned.

Small differences but they can make a huge difference when being used in a real world environment especially when considering if an arrays elements will constantly be changing. I hope this was helpful, happy coding !!

The sassy developer