Functional Programming in JavaScript

NC Patro
codeburst
Published in
5 min readMar 18, 2018

In this article, we will learn about declarative pattern, pure function, Immutability and side effects.

Dawn is the best time to learn

What is Functional Programming

  • In computer science, functional programming is a programming paradigm or pattern (a style of building the structure and elements of computer programs)
  • Functional Programming treats computation as the evaluation of mathematical functions.
  • Functional Programming avoids changing-state and mutable data.

The above definition is taken from Wikipedia, now let’s try to understand the value and benefits of FP(functional programming) in this article.

Other Major programming paradigm or pattern

  • Procedural Programming
  • Object Oriented Programming
  • Meta Programming
  • Imperative Programming
  • Declarative Programming

Procedural Programming based upon the concept of the procedure call, simply 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.

Imperative Pattern vs Declarative Pattern

  • Imperative Pattern focuses on describing how a program operates, it consists of commands for the computer to perform.
  • Declarative Pattern focuses on what the program should accomplish without specifying how the program should achieve the result.
  • Functional programming follows declarative pattern.
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);
  • In the above code snippet, we have added new attributes to each book(element) of books array and it has implemented in two different approaches.
  • First approach is with help of 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.
  • Second approach is with help of native JavaScript array method 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.

Mathematical Function or Pure Function

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 functions 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

Why Functional Programming

  • Its pure function, provides confidence of not changing things outside of its scope.
  • Its reduces the complexity, need not to worry about how it is doing it, focus will be only on what it is doing.
  • Ease of testing, because it does not depend on state of the application and result verification also will be easy.
  • It makes the code more readable.
  • Functional programming makes code easier to understand.

Examples of Functional Programming

Array Functions

Functional Programming

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.

  • find
  • map
  • reduce
  • every
  • some

Refer this github repo for the usage of above methods https://github.com/npatro/functional-programming/tree/master/code

Function Chaining

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.

Function Chaining

In the above code snippet, we want to print total members of all active meetups, considering 10% members might be duplicate.

Libraries to support FP

There are libraries which provide utility functions to make code more declarative.

  • RamdaJS
  • UnderscoreJS
  • lodash

Side Effects

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 function publishMeetup 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

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.

Immutable Libraries

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.

  • Seamless-immutable
  • Immutable JS

Summary

The main aspects of Functional Programming is Pure and smaller Functions, Immutability and less Side Effects.

If you like this post and it was helpful, please click the clap 👏 button multiple times to show support, thank you.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by NC Patro

Developer | Mentor | Public Speaker | Technical Blogger | Love for Photography and Programming | twitter: @ncpatro

Responses (8)

What are your thoughts?

Good read, but rather basic and incomplete. I would like to point out few things. Just please bare in mind I’m not a functional paradigm expert 😊
There are some things inherently related with functional programming that you did not mention.
One thing…

--

I would prefer to remove the return from 1 line arrow functions. It improves the readability of the examples.

--

Very well thought blog. This really helps

--