Functional Programming in JavaScript

Functional Programming in JavaScript

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

What is Functional Programming

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

Imperative Pattern vs 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);

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

Why Functional Programming

Examples of Functional Programming

Array Functions

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

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.

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.

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

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.

Summary

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

Originally published by NC Patro at https://codeburst.io

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ Vue.js Authentication System with Node.js Backend