Functional alternative to loops

Functional alternative to loops

With new functional features adding up in languages like java, it is good to know how to loop in a functional way. Following are some of functional alternative for ‘for’ loop which you can use

Using Map

The below code looks pretty familiar, right? You see that the for loop is taking each element from the array, performing some operation (here it is multiplying numbers), and putting that into a new array.

Array.map is a builtin function which returns a new array by transforming each element of the source array to a new value based on the supplied method for transformation.

It loops over all the elements in order, calling a supplied transformation function for each element, and internally pushes the results into a new array. We just need to supply the transformation function, and the rest of the work will be done by the map function. For example:

In simple terms, Array.map() transforms a given array into a new one after performing the transformation function on each element in the array.

Leave a Reply

Your email address will not be published. Required fields are marked *