DEV Community

Ankit Kumar for Tech Talks

Posted on • Updated on

Functional Programming Principles in JavaScript

Before going to it’s principles, let first understand a bit about it.

What is Functional Programming

Functional programming is a paradigm which has its roots in mathematics, primarily stemming from lambda calculus.
Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”.
Functional programming aims to be declarative and treats applications as the result of pure functions which are composed with one another.

The primary aim of this style of programming is to avoid the problems that come with shared state, mutable data and side effects which are common place in object oriented programming.
Functional programming tends to be more predictable and easier to test than object oriented programming but can also seem dense and difficult to learn for new comers but functional programming isn’t as difficult as it would at first seem.


Why do we need Functional Programming?

There are a few major benefits to Functional Programming and minor drawbacks:

Advantages:

  • More readability, thus maintainability
  • Less buggy, especially in concurrent contexts
  • A new way of thinking about problem solving
  • (Personal bonus) Just great to learn about!

Drawbacks:

  • Can have performance issues
  • Less intuitive to work with when dealing with state and I/O
  • Unfamiliar for most people + math terminology that slows the learning process

Functional programming tends to be more predictable and easier to test than object oriented programming.


Principles

On broader level, there mainly 6 principles of Functional Programming

  • Purity
  • Immutability
  • Disciplined state
  • First class functions and high order functions
  • Type systems
  • Referential transparency

Lets see them in details below.

Purity

  • A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed.
  • It does not depend on any state or data change during a program’s execution. Rather, it only depends on its input arguments.
  • Also, a pure function does not produce any observable side effects such as network requests or data mutation, etc.
  • It has no side effects like modifying an argument or global variable or outputting something.
  • Pure functions are predictable and reliable. Most of all, they only calculate their result. The only result of calling a pure function is the return value.

Lets see an example below for calculating GST.

const calculateGST = (productPrice) => {
    return productPrice * 0.05;
}
Enter fullscreen mode Exit fullscreen mode
  • The computation in square function depends on the inputs. No matter how many times we call a square function with the same input, it will always return the same output. Example below
const sqaureIt= (number) => {
    return number * number;
}
Enter fullscreen mode Exit fullscreen mode

Immutability

  • Immutable data cannot change its structure or the data in it.
  • Once you assign a value to something, that value won’t change.

Immutability is at the core of functional programming. This eliminates side effects (anything outside of the local function scope), for instance, changing other variables outside the function.

  • Immutability helps to maintain state throughout the runtime of a program.
  • It makes code simple, testable, and able to run on distributed and multi-threaded systems
  • Since function has a disciplined state and does not change other variables outside of the function, we don’t need to look at the code outside the function definition.
  • Immutability comes into play frequently when we work with data structures. Many array methods in JavaScript directly modify the array.

For example, .pop() directly removes an item from the end of the array and .splice() allows you to take a section of an array.

// We are mutating myArr directly
const myArr = [1, 2, 3];
myArr.pop();
// [1, 2]
Enter fullscreen mode Exit fullscreen mode

Instead, within the functional paradigm, we would copy the array and in that process remove the element we are looking to eliminate.

// We are copying the array without the last element and storing it to a variable
let myArr = [1, 2, 3];
let myNewArr = myArr.slice(0, 2);
// [1, 2]
console.log(myArr);
Enter fullscreen mode Exit fullscreen mode

Disciplined state

  • Disciplined state is the opposite of shared, mutable state.
  • A shared mutable state is hard to keep correct since there are many functions that have direct access to this state. It is also hard to read and maintain.
  • With mutable state, we need to look up for all the functions that use shared variables, in order to understand the logic. - It’s hard to debug for the very same reason.
  • When we are coding with functional programming principles in mind, you avoid, as much as possible, having a shared mutable state.
  • Of course we can have state, but you should keep it local, which means inside our function. This is the state discipline : we use state, but in a very disciplined way.

An example of the drawbacks of shared, mutable state would be the following:

const logElements = (arr) => {
  while (arr.length > 0) {
    console.log(arr.shift());
  }
}

const main = () => {
  const arr = ['Node', 'React', 'Javascript', 'Typescript'];

  console.log('=== Before sorting ===');
  logElements(arr);

  arr.sort();

  console.log('=== After sorting ===');
  logElements(arr);
}

main();

// === Before sorting ===
// "Node"
// "React"
// "Javascript"
// "Typescript"

// === After sorting ===
// undefined
Enter fullscreen mode Exit fullscreen mode

We can see that the second call produces no result since the first call emptied the input array and thus mutated the application state generating an unexpected output.

To fix this we turn to immutability and the use of copies to keep the initial state transparent and immutable.

const logElements = (arr) => {
  while (arr.length > 0) {
    console.log(arr.shift());
  }
}

const main = () => {
  const arr = ['Node', 'React', 'Javascript', 'Typescript'];

  console.log('=== Before sorting ===');
  logElements([...arr]); // Change in line

  const sorted = [...arr].sort(); // Assign sorted items to another variable

  console.log('=== After sorting ===');
  logElements([...sorted]); // Change in line
}

main();

// === Before sorting ===
// "Node"
// "React"
// "Javascript"
// "Typescript"

// === After sorting ===
// "Javascript"
// "Node"
// "React"
// "Typescript"
Enter fullscreen mode Exit fullscreen mode

First class functions and high order functions

Higher order functions are functions which do at least one of the following:

  • Takes one or more functions as arguments
  • Returns a function as its result

Functional programming treats functions as first-class citizens.

This means that functions are able to be passed as arguments to other functions, returned as values from other functions, stored in data structures and assigned to variables.

const plusFive = (number) => {
  return number + 5;  
};

// f is assigned the value of plusFive
let f = plusFive;

plusFive(3); // 8

// Since f has a function value, it can be invoked. 

f(9); // 14
Enter fullscreen mode Exit fullscreen mode

Higher order function is the function that takes one or more functions as arguments or returns a function as its result.


Type systems

By using types we leverage a compiler to help us avoid common mistakes and errors that can occur during the development process.

With JavaScript we could do the following:

const add = (left, right) => {
  return left + right;
}

add(2, 3) // 5
add(2, "3"); // "5"
Enter fullscreen mode Exit fullscreen mode

This is bad because now we are getting an unexpected output which could have been caught by a compiler.

Let’s look at the same code written with Typescript:

const add = (left: number, right: number): number => {
  return left + right;
}

add(2, 3) // 5
add(2, "3"); // error!
Enter fullscreen mode Exit fullscreen mode

Here we can see the compiler in action protecting us from such basic issues, of course much more is possible with a statically typed approach to developing but this should give you the gist of why it is useful to use.


Referential transparency

  • Referential transparency is a fancy way of saying that if you were to replace a function call with its return value, the behaviour of the programme would be as predictable as before.

  • Referentially transparent functions only rely on their inputs and thus are closely aligned with pure functions and the concept of immutability.

  • An expression is said to be referentially transparent if it can be replaced with its corresponding value without changing the program’s behaviour.

  • To achieve referential transparency, a function must be pure. This has benefits in terms of readability and speed. Compilers are often able to optimise code that exhibits referential transparency.

const two = () => {
  return 2;
}

const four = two() + two(); // 4
// or
const four = two() + 2; // 4
// or
const four = 2 + two(); // 4
// or
const four = 2 + 2; // 4
Enter fullscreen mode Exit fullscreen mode

Conclusions

Functional programming gives us some principles which make our code more readable, predictable and testable.

This allows us to have code which contains less bugs, easier onboarding and a generally nicer codebase from my experience.


Also, to be notified about my new articles and stories: Follow me on Medium.

Subscribe to my YouTube Channel for educational content on similar topics

Follow me on Medium and GitHub for connecting quickly.

You can find me on LinkedIn as it’s a professional network for people like me and you.

Cheers!!!!

Top comments (11)

Collapse
 
zelenya profile image
Zelenya • Edited

Nice article 🙏

A minor note: mentioned drawbacks are mostly myths; for instance, can have performance issues isn't true. If the language performs poorly for some FP construct (usually, it should be optimized), it's a language issue, not some global FP issue.

Also, you can highlight the code snippets if you add the language after the ticks: '''javascript

Collapse
 
architectak profile image
Ankit Kumar

Thanks for the suggestion and insightful information on drawbacks.

Collapse
 
thumbone profile image
Bernd Wechner • Edited

My hands-on introduction to Functional programming has been OpenSCAD, building a 3D model of our house and land. Diving in, and my first realisation and introduction to the fact that it was Functional, was when I set a variable, and changed its value later, but found it had the latter value before I'd set it ... when it was used above that, when I expect it to have the first value set. Took a step back and whooooaa, did some reading and learned some. Then I remember well the next hurdle was that I couldn't write a loop, no iteration ... well, because containers are immutable (not variables per se at all) and so there is no for i ... as i has one value and one value only. So every thing you would instinctively do in a loop demands a recursive solution - and recursion takes on a whole new role, no longer a semi risky thing (of an overflowing a stack) but a central mechanic for solving any sort of repetitive problem.

It sure takes some getting used to, I'll grant that.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
ymahendraa profile image
ymahendraa

Thanks for made a great article pal

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

JS is fun...

const squareIt = (number) => {
    return number * number;
}
const myInput = { valueOf() { return performance.now() }}

console.log(squareIt(myInput)) // 6046681
console.log(squareIt(myInput)) // 6056521
Enter fullscreen mode Exit fullscreen mode

Pure(?) function - same input, different outputs 👍

Kind of a 'trick' - I know - but the input is identical each time. Because of this, in the strictest sense, it can be considered that functions such as these are not pure - as there are possible inputs that will wreck the purity.

Collapse
 
architectak profile image
Ankit Kumar

const squareIt = (number) => {
    return number * number;
}
const myInput = { valueOf() { return performance.now() }}

console.log(performance.now()) // 132161.5
console.log(squareIt(myInput)) // 17466767811.611576
console.log(performance.now()) // 132162
console.log(squareIt(myInput)) // 17466847108.83685

Enter fullscreen mode Exit fullscreen mode

JS is fun, since input is changing its value on each call, hence output is different

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

But the input to the function is the same. The calculation differs because of coercion that happens as a feature if JS. The inputs themselves are unchanged. The input in this case is an object with a single method.

Thread Thread
 
architectak profile image
Ankit Kumar

In input of function is function that keeps changes its value, then that function can not be considered as pure function, right ?

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The input is an object, but it's value upon coercion to a number differs on each coercion. In a very strict sense, such a simple function could be considered impure. To make it strictly pure in JS, you could add a bunch of code checking types etc.

Collapse
 
jackmellis profile image
Jack

Put simply, the input itself is impure. The valueOf getter uses performance.now which is external state (calling valueOf with the same inputs does not return the same result every time). When you introduce impure inputs then you’ve already broken the fp paradigm.