es6 Methods Map and forEach

andrew leachman
Sep 5, 2018 · 1 min read

What is the difference between the map and forEach methods in javascript?

The forEach method loops through the array ‘for each’ element inside the array and allowing you to directly change the items in the array using the parameters. Imagine the computer thinking, “I will return element + 2 ‘for each’ element in the array”.

The map method however doesn’t effect the array directly, instead the map method creates an entirely different array using the elements inside the original array. The computer iterates through each of the elements and pushes them into a new array after running them through your function. This method is valued because when a large app or program collects information from the user, it avoids altering that information as best as possible, this allows them to use the original information without changing or loosing the original elements.

Each of these methods have their own use, and are better or worse for specific tasks, you may want to use the forEach methods for a value that is always changing like your balance in a game, but you might not want to use it to store user login info because that might alter their ability to log into the website. Map method would be great for this though, but would create to many different arrays when it came to some sort of balance.