Master functional programming in JavaScript to write more efficient, reusable, and maintainable code. Learn about pure functions, immutability, and other key concepts of functional programming, and see how to apply them in your JavaScript code.
In this article, we will learn about declarative pattern, pure function, Immutability and side effects.
The above definition is taken from Wikipedia, now let’s try to understand the value and benefits of FP(functional programming) in this article.
Procedural Programming based upon the concept of the procedure call_, s_imply contain a series of computational steps to be carried out. Any given procedure might be called at any point during a program’s execution, including by other procedures or itself. Major procedural programming languages are COBOL, BASIC, C, ADA and GO
Object Oriented Programming based on the concept of objects, which contains data(attributes) and procedures(methods). This pattern is more closer to Functional Programming. Significant object-oriented languages include C++, Java, PHP, C#, Python, Ruby, Swift etc.
Meta Programming have the ability to treat programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running.
var books = [
{name:'JavaScript', pages:450},
{name:'Angular', pages:902},
{name:'Node', pages:732}
];
/* Imperative Pattern */
for (var i = 0; i < books.length; i++) {
books[i].lastRead = new Date();
}
/* Declarative Pattern */
books.map((book)=> {
book.lastReadBy = 'me';
return book;
});
console.log(books);
for loop
, iterating over the array based on its length, then checking array index counter against array length and incrementing the index counter on each iteration. So, this is more like program/code is focusing or describing on how to operate for the desired output.map()
which takes function as argument and that function gets each element. So in this case code is not describing about how to operate but talking about what to accomplish and map()
method behind the scene takes care of actual operation.In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input combination is related to exactly one output.
In functional programming, these kinds of functions called pure function which only depends on the received input data to the function and does not alter the input data except the returned data.
Math.random()
is not pure function because it always returns new value on each call.
Math.min(1,2)
is an example of pure function which always returns same value with same set of inputs
In the above example, we are trying to filter only active meet-ups and we can see it can be achieved with two different approach. Here, second approach is Functional Programming where filter()
method takes care of “how program operates” and program focuses only on input i.e. meetups
array and care about output activeMeetupsFP
but in first approach program cares about how to operate as well with for
loop.
Similarly, below are other Array methods which help to achieve functional programming and reduce the complexity of the code.
Refer this github repo for the usage of above methods https://github.com/npatro/functional-programming/tree/master/code
It’s a mechanism for invoking multiple method calls, each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
In the above code snippet, we want to print total members of all active meetups, considering 10% members might be duplicate.
There are libraries which provide utility functions to make code more declarative.
Function or expression is said to have a side effect if it modifies some state of the program, which is outside of its own scope or has an observable interaction with its calling functions or the outside program besides returning a value.
let meetup = {name:'JS',isActive:true,members:49};
const scheduleMeetup = (date, place) => {
meetup.date = date;
meetup.place = place;
if (meetup.members < 50)
meetup.isActive = false;
}
const publishMeetup = () => {
if (meetup.isActive) {
meetup.publish = true;
}
}
scheduleMeetup('today','Bnagalore');
publishMeetup();
console.log(meetup);
The program is having side effect because the actual responsibility of function scheduleMeetup
is to add the date
and place
of the meetup
but it’s modifying the value of isActive
as well on which some other functionpublishMeetup
is depended upon and as a side effect the publishMeetup
function will not have desired output because it’s input has changed in between. In the big program (real program), it’s really tough to debug the side effects.
Side effects are not always bad but we should be careful on when to have it.
Immutability is important to make sure one function does not change the original data rather than should return new copy of the data after manipulation.
Like if Array and Objects are passing around multiple functions and we are not maintaining immutability then functions might not get the original copy of the array and object.
It is really hard to debug if something goes wrong in case of mutable object and array.
Mutability is not bad but it should be when to have it.
JavaScript by-default does not provide anything to make the object and array Immutable. There are libraries which can help us to achieve the immutability.
The main aspects of Functional Programming is Pure and smaller Functions, Immutability and less Side Effects.
#javascript