DEV Community

Aaron McCollum
Aaron McCollum

Posted on • Updated on


October Updates - Functional Programming!

What a month! It has been awhile since I last wrote a blog post but I have not forgotten about it! A lot has happened in the past month and a half, however I’m back to coding and going through freeCodeCamp’s JavaScript course. Right now I am going through the Functional Programming lessons/exercises with much difficulty. One thing to note about the freeCodeCamp JavaScript course is that it definitely ramps up in complexity as you continue.

But it has been helpful! In the past week, I have put effort into learning, Array.filter(), and Array.forEach(). These three functions are built in and newer to the JavaScript language, however I can already tell they are three extremely popular functions to use. On one subreddit post a few days ago, I saw where most programmers don’t really use for-loops anymore and usually use one of the three functions above when needing to iterate through the contents of an array. In case you are also wondering what the differences are, below is what I’ve learned:
The map() function will iterate through a relay and run a function on every single item in the array. With each iteration, it will then return all the results (each individual result of the function acting on the array item) into a new array. Since the map() function does not alter the original array, this is a popular function for “functional programming.”

For example, if you have arrayA = [2, 3, 4, 5] and you run a map() function that doubles each value, the map() will return a new array with [4, 6, 8, 10].

The forEach() function is very similar to the map() function. It also will iterate through a relay and run a function on every single item in that array. However, unlike the map() function, the forEach() function will alter the original array. Instead of returning a new array, it will instead run the function on the original array and alter each item as a result.

For example, if you have arrayA = [2, 3, 4, 5] and you run a forEach() function that doubles each value, the new result is arrayA = [4, 6, 8, 10]. (Compare this to the map() example above where a new array is returned)

The filter() function will iterate through the items of an array, much like the map() and forEach() functions above. It will run a function on each item in the array, however this time the function result for each array item will be either true or false. Does the array item fit the desired result? If the function returns true, the array item will be pushed to a new array with all the other “true” array items.

What helped me out?
I found a few YouTube videos that helped me with map(), filter(), and forEach() – they are linked below.

JavaScript Array.forEach()
JavaScript Array.filter()

(Originally published on my personal blog).

Top comments (0)