Principles of Functional Programming
Tags: functional, beginners, javascript
Published: 2020-02-25 15:39:51

Functional programming is a paradigm which has its roots in mathematics, primarily stemming from [lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus). 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](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) 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.

## The principles of Functional Programming

The aim of this article is look at the basic principles of functional programming and to clarify what functional programming is and what it stands for which should produce some clarity on the subject for those of you who are newcomers and a good refresher for everyone else.

### Pure Functions

A pure function is a function which:

1. Given the same inputs, always returns the same output
2. Has no side-effects

```javascript
// pure
function getSquare(x) {
   return x * x;
}

// impure
function getSquare(items) {
  var len = items.length;
  for (var i = 0; i < len; i++) {
    items[i] = items[i] * items[i];
  }
  return items;
}
```

Basically, any function that changes its inputs or the value of some external variable is an impure function.

### No side effects

[Side effects](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) are treated as evil by the functional programming paradigm. Side effects are things such as [I/O](https://en.wikipedia.org/wiki/Input/output), logging to the console, thrown and halted errors, network calls and the alteration of an external data structure or variable. Basically anything which makes a system unpredictable.

In saying this, functional programming doesn't say you can't have side effects since they are required at times but it aims to reduce the occurrence of such effects as much as is possible.

If a function contains side effects, it is called a procedure.

### Immutability

Immutability is at the core of functional programming. Immutability is the idea that once a value is declared, it is unchangeable and thus makes behaviours within your programme far more predictable.

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

For example:

```javascript
function 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
```

All of these ways of generating the variable `four` show that the function `two` is referentially transparent since I can replace calling it with its return value and the programme would execute as expected.

### Functions as first-class entities

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

For example I could do the following since JavaScript treats functions as first class entities:

```javascript
function add(left, right) {
 return left + right;
}

const adder = add;

adder(2,3);
```

### Higher order functions

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

1. Takes one or more functions as arguments
2. Returns a function as its result

We have already some higher order functions in my previous articles such as those on [Array Map](https://dev.to/jamesrweb/array-map-4en), [Array Filter](https://dev.to/jamesrweb/array-filter-3ij5), [Array Reduce](https://dev.to/jamesrweb/array-reduce-2bfh) and [Array Sort](https://dev.to/jamesrweb/array-sort-50k5).

All other functions are called first order functions.

### Disciplined state

Disciplined state is the opposite of shared, mutable state. An example of the drawbacks of shared, mutable state would be the following:

```javascript
function logElements(arr) {
  while (arr.length > 0) {
    console.log(arr.shift());
  }
}

function main() {
  const arr = ['banana', 'orange', 'apple'];

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

  arr.sort();

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

main();
// Before sorting:
// "banana"
// "orange"
// "apple"
// After sorting:
// undefined
```

> Credit to [2ality](https://2ality.com/2019/10/shared-mutable-state.html) for this example.

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.

```javascript
function logElements(arr) {
  while (arr.length > 0) {
    console.log(arr.shift());
  }
}

function main() {
  const arr = ['banana', 'orange', 'apple'];

  console.log('Before sorting:');
  logElements([...arr]);

  const sorted = [...arr].sort();

  console.log('After sorting:');
  logElements([...sorted]);
}

main();
// Before sorting:
// "banana"
// "orange"
// "apple"
// After sorting:
// "apple"
// "banana"
// "orange"
```

Encapsulation of state within individual functions, not changing external state or data structures and making use of shallow or deep copies and inputs will help you keep your state disciplined and predictable.

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

```javascript
function add(left, right) {
  return left + right;
}

add(2, 3) // 5
add(2, "3"); // "5"
```

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 [flow type](https://flow.org/en/) annotations:

```javascript
function add(left: number, right: number): number {
  return left + right;
}

add(2, 3) // 5
add(2, "3"); // error!
```

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.

## 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. In the following articles we will be looking at some functions which will help us develop more function driven applications.