Functional Programming in JavaScript
forEach, map, filter, reduce, find, findIndex, some & every
Found a typo? Edit meFunctional Programming is a paradigm where programs are constructed by applying and composing functions. The Functional Programming keys are:
- You treat functions as first-class citizens.
- You can pass them as arguments to other functions.
- A function can return another function.
- You can modify functions.
When a function is called with some given arguments, it will always return the same result, and cannot be affected by any mutable state or other side effects.
And now, we are going to take a look at the most common JavaScript functions that allow us to write Functional Programming: forEach, map, filter, reduce, find, findIndex, some and every.
For Each 🧩
We use forEach() when we like to iterate through an array of items.
Using this method, you can get the item of the current element when iterating and/or the index.
It is recommendable not to use it unless you are sure you want to modify the original array. This method is mutable. It
means it will modify the original array.
index,
--OUTPUT--
0 "SPAIN"
1 "GERMANY"
2 "PORTUGAL"
3 "FRANCE"
Map 🗺
We use map() whenever we want to map the values into other values producing a new array.
mapped
--OUTPUT--
Filter ⌛️
We use filter() when we want to pick just some specific elements regarding a filter. It returns a new array with the filtered elements or empty if no matches.
filtered
--OUTPUT--
Reduce ⛏
We use reduce() when we want to return a single value depending on a specific closure. This function can take an initial value, which by default is empty (0 or "") as the second parameter.
sum
--OUTPUT--
60
find 🔎
We use find() if we are interested in the first occurrence of a certain element in an array. It will return undefined otherwise.
find
--OUTPUT--
"Germany"
find Index 🔑
We use findIndex() if we would like the first occurrence of a certain element in an array, this method is pretty similar to find but it will return not the value but the index. In case there are no matches, the output would be -1.
findIndex
--OUTPUT--
1
Some 🧵
We use some() if we are interested to know if some element from an array meets a specific closure. If any of the items satisfy the criteria the result will be true, else, it will be false.
isAn
isLand
--OUTPUT--
true
false
Every ☘️
We use every() if we want to know if every element from an array meets a specific closure. This method is somehow similar to some but the opposite. This method also returns true or false.
isEveryA
isEveryE
--OUTPUT--
true
false
These are the most common functions when dealing with Functional Programming, but there are many more (fill, join, sort, etc). You can easily check the full list on the Mozilla Developer 🦊 site.