Functional Programming is a programming paradigm of building the structure and elements of computer programs that treat computation as the evaluation of mathematical functions and avoids changing state and mutable data.
FP is categorized as a declarative programming paradigm rather than an imperative one. This implies that FP focusses on WHAT you want to achieve without worrying about the HOW (processes and algorithms working towards that particular goal).
Imperative paradigm example: Get the sum of elements in an array.
With Functional Programming, the declarative approach to getting the sum of elements in an array would only worry about what we want to do rather than how to achieve it. Here goes:
As seen above, we wrote fewer lines of code with FP and did not have a lot of implementation details to worry about. We used the
array.reduce() method that accepts an accumulator argument and another to hold the array elements. The accumulator argument saves the value of the previous iteration and eventually holds the final sum. This saves us a lot of mental effort as compared to our imperative approach.
Functional Programming has a few core concepts to constitute it. These include:
- Pure Functions
- First Class Functions
- Side Effects
Pure Functions are those that do not depend on data other than what is passed in and don’t alter data other than what is returned. Pure functions will always return the same value when given the same arguments. Using Pure functions makes it easier for you to test your application as whatever is returned is pure, absolute and concise.
First Class Functions are assigned to a variable and passed as arguments to other functions.
Immutability refers to the unchanging state of an object once it has been created. Immutability is what gives rise to the reduction of programming side effects. With FP and immutability, you do not have to worry about receiving unexpected state that breaks code as the state was mutated by one of your methods that you can’t track down while debugging.
So where in our code should we use FP? The for loop is a sure indicator that we can introduce some FP to simplify our code and make it easier to read and think about. Let's dig into some imperative vs declarative examples to show you how FP gives us less to think about when writing our code.
As seen above FP is winning in terms of code complexity, mental effort and the number of lines of code written. There are other array methods worth checking that neatly implement FP. I would recommend you check out:
Array.prototype.some. If you're interested in exploring this with a Js library, Ramda.js and Lodash_fp would be a perfect place to start.
These are just but a tip of the iceberg in terms of what FP is and what we can do with it. I hope you are now thinking of doing away with those endless nested for loops 😃. Until next time, happy coding.