Functional Programming in Javascript

What is Functional Programming?

This question can be answered in many ways, let’s start with the basics of functional programming.

  • Functional Programming is one of the programming paradigms whereas some other programming paradigms are Imperative programming and Object Oriented Programming.
  • Functional Programming is a paradigm where functions are kings, it is one of the ways in which we can approach any task or the problem.
  • Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects.
  • FP is declarative rather than imperative and application state flows through pure functions.
  • Functional code tends to be more concise, more predictable and easy to understand that the imperative or the object-oriented programming.
  • There are a lot of people and libraries out there to help you out with the functional programming.

The idea of functional programming is to express everything in terms of functions. And a function is, of course, a function that takes an input and gives an output.

So, we have to think about how the data flows through the various functions rather than thinking about how the objects interact.
Let’s see the following example which is non-functional:

var name="Sharad";
var message="Hey I'm ";
console.log(message+name);
output:
Hey I'm Sharad

So, if we look at the above code, we can say that it is the imperative style of programming where we execute step by step. We have no functions in the above code.

Let’s see the functional way of doing this:

function message(name){
return "Hey i'am "+name;
}
message("Sharad");

The functional programming avoids the side effects by using the functional programming.

What I mean by side-effects is, if a function takes an input and returns the output which is not according to the input.

For instance, if any functions take anything from outside the function and involve it inside the function, then they aren’t pure functions.

The idea of pure functions is it should return the same output for the same input. For instance, if you pass ‘2’ and ‘3’ in functions, the sum of them should return as ‘5’

Let’s see the below example which is not a pure function:

var name="Sharad"

function message(){
return "Hey i'am "+name;
}
message();

As we can see, we are involving a global variable called “name” inside the function, it should not be considered as a pure function.

To check how the code looks for the above function, check the following:

function message(name){
return "Hey i'am "+name;
}
message("Sharad");

The function returns the output based on the input we have passed.

We can also have Higher-order functions where we pass one function to another and so on.

Let’s see the following:

fucntion fullName(fName){
returns function(lName){
return fName+" "+lName;
};
}
var name= fullName("Sharad");
name("Pawar");
output:
Sharad Pawar

The above function returns another function and both the functions are taking one input parameters each and returning the full name. These type of functions are called Higher-order functions where one function can return one or more functions.

Avoiding Iterations:

So, other things which we are going to avoid are the iterations like for, if etc., for which we use map, reduce, filter kind of terminology.

The idea here is we have a list of vegetables and we have to transform it in a way to make a sandwich. So, we have vegetables and we have a slice functions where we are slicing all the vegetables which we can apply to all list of items. Here we are mapping all the list items and let’s say we have a chop function where we are slicing all the vegetables and returning back from the chop function. Then, we have something called reduce where it will combine all the chopped items layer by layer and make a sandwich. We also have a filter function, it comes into play when let’s say you hate cucumber and you don’t want it into your sandwich so the filter will help you to prepare your sandwich without cucumber.

So, the above examples show how we transform our list using map, reduce, filter technique.

Avoiding Mutability:

These are the another concept where we avoid mutation of data.
Mutation will be considered as non-functional, let’s see the below example:

var rooms=['A','B','C'];
rooms[2]='D';
rooms;
output :
["A" ,"B", "D"]

So, these are called mutation, here we are doing modification in the original list. If we modify the original list, it will cause several issues or bugs, the reason is the above array might have been used at multiple places in real time programming. This is one of the most important reasons why functional programming avoids mutation in the data. So, instead of changing the original array, let’s see how we can add the room D?

var rooms=['A','B','C'];
var newRooms=rooms.map((rm)={
if(rm==='C') return 'D'
else return rm;
});
newRooms = ['A','B','D'];
rooms= ['A','B','C'];

Instead of modifying the original data we have created a new array and added a room called ‘D’ in a newRooms array. This is for avoiding the data mutation. So, if we look at the above example we can see that copying array is not the solution for our problem it will cause a lot of efficiency issues in the real time.

We cannot go and copy the array every time, processing array is not the solution, it will cause a lot of memory wastage and we have to process all the elements in the list.

One way of avoiding the above issue is by using the persistent data structures.

Persistent Data Structures to avoid Mutability:

In order to use persistent data structures, we have to use some of the libraries like Mori, Immutable JS etc. These two libraries are well known so we can proceed with any of them as per your choice.

So, the next question comes in mind when we talk about Persistent DS is how they really work.

Let’s say we have the following array
[“H1″,”H2″,”H3”]
Let’s say we want to replace H3 with H4.
[“H1″,”H2″,”H4”]
It will replace only H3, it won’t affect the other elements. It will just replace the H3 node.
The libraries which we have mentioned above come with all help functions like map, reduce etc.

Let’s take another example, using the Persistent Data Structures.

var vehicles = [
{ make: 'Honda', model: 'CR-V', type: 'suv', price: 24045 },
{ make: 'Honda', model: 'Accord', type: 'sedan', price: 22455 },
{ make: 'Mazda', model: 'Mazda 6', type: 'sedan', price: 24195 },
{ make: 'Mazda', model: 'CX-9', type: 'suv', price: 31520 },
{ make: 'Toyota', model: '4Runner', type: 'suv', price: 34210 },
{ make: 'Toyota', model: 'Sequoia', type: 'suv', price: 45560 },
{ make: 'Toyota', model: 'Tacoma', type: 'truck', price: 24320 },
{ make: 'Ford', model: 'F-150', type: 'truck', price: 27110 },
{ make: 'Ford', model: 'Fusion', type: 'sedan', price: 22120 },
{ make: 'Ford', model: 'Explorer', type: 'suv', price: 31660 }
];
var averageSUVPrice = vehicles
.filter(function(v){ v.type === 'suv'})
.map(function(v){ v.price})
.reduce(function(sum, price, i, array) { sum + price / array.length, 0});
console.log(averageSUVPrice); // 33399

So, this is all about Functional programming in JavaScript.

To know more about what we do and who we are, visit our website: www.wavelabs.in