Iterating in Java Script Using .Map

Michael Stephens
2 min readSep 19, 2021

What is iteration, The Oxford dicitonary defines iteration as “repetition of a mathematical or computational procedure applied to the result of a previous application, typically as a means of obtaining successively closer approximations to the solution of a problem”. In computer programming use often use iteration as means to parse through data in an array to find elements within the array that meet a give criteria. Additionally, we can also use iteration to apply functions to to data in an array through the use of the collection method in Javascript. In this article we will be examining the map() method and comparing it to the forEach() function.

The easiest way to visualize what happens when we use the map() is to use it to perform a mathematical function to numbers in an array.

const arrayNum = [100, 49, 12222, 25]const squareRootNum = arrayNum.map(number => Math.sqrt(number))console.log(squareRootNum)> Array [10, 7, 110.55315463612968, 5]

As you can see from the example above, map() takes in the square root function and applies it to the elements in the array. A new array is then created with the square root of each element in the original array. It is important to note that map() creates a new array and does not modify the original array which makes it an important tool when try to create DRY(Don’t Repeat Yourself) code.

map() v.s forEach()

JavaScript has several other function that provide similar functionality to map(), one such function is the forEach() function. In fact the two methods are so simalar that there are very few things you can do with one that you cannot do with the other. Like map(), forEach() iterates over each element in an array but there are two main distinction. The first distinction is that unlike map(), forEach() does not create a new array. Because forEach() does not create a new array we will often time use it when we want to see the output in console.log().

Secondly, forEach() is considerred to be the most flexible and therefore least-Expressive collection method. Unlike the other common JavaScript collection methods like map, filter and reduce, forEach() does not convey the intent of the programmer when iterating over an array. For this reason it is good practice to use one of expressive methods whenever possible.

--

--