Simply put (rudimentary if anything), the functional programming style is to build up your program with functions, instead of objects and procedures.
Let’s take a example of very procedural code…
First, we’ll make some test data:
We have two arrays, both containing user objects. The aim is to find the difference between the arrays, ie. find the new user, and then make the new user(s) into real users (just
console.log their name).
A very procedural approach may look something like this:
As you can see, we need to declare two arrays, outside of our logic, and manipulate them from within the loops.
Let’s have another stab…
Taking a more functional approach, we’ve eliminated the need for any “state” arrays, as we’re holding all the logic inside our functions. The building blocks of our (albeit small) program are functions, not
for loops and variable declarations. We pipe the output of one “block” (
filter) as the input to our next “block” (
map). We don’t need to concern ourselves with whether there are any ‘new users’, as
.map won’t execute if there’s no output from the
23 lines of code down to 5
The obvious benefit from the above approach is conciseness; a drastic reduction in lines of code (not always the best metric to gauge code on, but applicable in this situation).
Hopefully you’ve seen that 1. functional programming isn’t all that daunting and 2. that you can gain a lot (or reduce a lot of code) from sprinkling some functional techniques into your programs.