skip to Main Content
Functional Programming In Javascript & NodeJS, Explained With Example

Spread the love

Functional programming (FP), the term is very obvious for Haskell, Scala, Elixir, Lisp programmers. If you are a javascript developer and new with functional programming then bear with me till the end. I’m introducing a new way of structuring your code and thinking functionally.  It would help you to build your applications in a maintainable, reliable and safe manner.

What is functional programming

Functional programming, in short FP is a style of programming where computations are treated as the evaluation of mathematical functions. This programming paradigm avoids mutable state and mutable data. FP is based on lambda calculus, therefore any data inside the application cannot be changed. Only it can be copied somewhere else and we may only modify the copy of the original data. Most importantly, inputs are transformed into output without modifying the given input.

Simply put, functional programming is composing a set of small reusable functions

How Javascript Or NodeJS fits into functional programming?

First of all, Javascript isn’t actually a functional programming language. Furthermore, it may not be a good choice for learning FP. But it’s a multi-paradigm language, means flexible and powerful for any type of programming methodology you want. Certainly, it’s worth taking the leap into a new challenge to write a functional code in javascript.

Many people also look for functional programming in NodeJS. Similar to javascript, now you know FP has nothing strictly bound with NodeJS itself. However, you can definitely achieve functional approach of coding in Node.

Concepts of functional programming

The hard part is getting used to with few unfamiliar terminologies that makes your code functional, such as:

  • Side Effects
  • Pure Functions
  • Functions as first class citizens
  • Higher Order function
  • Currying

Now let’s get into these new concepts of functional programming one by one. Make sure you forget whatever you know about wiring an imperative code in javascript.

What is Side Effect?

A function or expression is considered to have side effects if it access or updates outside states of its local scope.

Example Of Side Effects: Anything that accesses outside of the function, For example:

  • Database Operations (CRUD)
  • Reading or writing a file
  • Accessing or modifying global variables/states

What is a pure function?

A function is called a pure function when it always returns the same output for the given input and it should not have any side-effect

// pure function
function fullName(fname, lname){
  return fname + " "+ lname;
}

// impure function
var fname = "Node";
var lname = "function";

function getFullName(){
  // using external variables, side-effects
  return fname + " "+ lname;
}

Functions as first class citizens

 In JavaScriptfunctions are first-class objects, because they can have properties and methods just like any other object

 — MDN

JavaScript treats functions as first-class citizens. As a result, functions in javascript can be assigned to a variable as it’s value. Like you can pass and return a variable, similarly, you can do so with the functions. This is what gives you a very natural approach to functional programming in javascript.

// function can be assigned to a variable
var load = function(){
  console.log("Done");
}

var fetch = load;

// fetch and load, both referring the same function
fetch();

What is a higher order function?

A higher order function is a function which takes one or more functions as arguments of the function Or returns a function as a result.

Javascript Example: Function passing as argument

document
  .getElementById("node-demo")
  .addEventListener("click", doStuffOnClick);

function doStuffOnClick() {
    console.log("CLICKED!");
}

Node.JS Example: Function passing as argument

var fs = require('fs');

fs.readFile("/pathPath", function(err, data) {
  if (err) throw err;
  console.log(data);
});

Example: Function returns another function

function adder(a){
  return (b) => {
    console.log(a+b)
  }
}
console.log(adder(5)(10)); // 15

Currying

Currying is a way of composing function where it takes on arguments at a time and returns another function. The returned function also takes one argument and return the same thing until final argument has passed. The last one in the chain returns the result of the function

// regular function
function add(a,b,c){
  return a+b+c;
}
add(1,2,3); // 6

// currying
function add(a){
  return function(b){
    return function(c){
      return a+b+c;
    }
  }
}
add(1)(2)(3); // 6

How does currying work?

Currying works by creating nested functions.  As inner function are being executed in the scope of the main function, it has access to all arguments given to the chain.

No Loop

Functional language does have any loops.

Wait, what? you got it right. No while, for loop in functional programming. Obviously, the next question is how am I supposed to iterate? well, Functional programming is all about functions and it iterates by recursion. We already are familiar with map(), filter() & reduce() functions which does this job. But why there isn’t any loop? Because a loop requires having a variable. As variables are mutable they are not pure. Most noteworthy, there is no such variable concept in FP

Javascript libraries for functional programming

If you like to give a shot on how functional programming would like in javascript then you can start with with any of the given below:

  • Ramda – A practical functional library which emphasizes a purer functional style in javascript
  • lodash/fp – Loadash has an implementation of a functional flavor where its methods wrapped to produce immutable, auto-curried, iterate-first, data-last methods.
  • functional.js – A lightweight functional JavaScript library that facilitates carrying and point-free / tacit programming.

Conclusion

All we learned about functional programming today is just a tip of an iceberg. Probably, It’s boring or frightening at the beginning, but all you need is a mindset to accept the charms. Let me know your thoughts below!

Functional Programming in Javascript & NodeJS, Explained with Example
4.8 from 8 votes

Spread the love

Ikrum Hossain

Live in code, Love in backend. A blogger by passion, a backend developer by blood and enthusiastic to explore new technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *

shares
Back To Top
×Close search
Search