Functional programming definition

Functional programming is a programming paradigm, like object object-oriented programming. Functional programming includes five practices.

  • Pure functions
  • Function composition
  • Avoiding shared state
  • Avoiding mutating state
  • Avoiding side effects

Pure functions

Function with no effects from outside and always same input arguments produce the same output. Also pure functions should not have effects to outside from itself.

const doubleIt = x => 2 * x;

doubleIt(2); // 4
doubleIt(2); // 4
doubleIt(4); // 8
doubleIt(2); // 2

As seen in example, this function doesn't get affected from outside. It doesn't affect anything else. It also returns always the same value with same parameter.

Function composition

Functions can be combined to produce new functions. This way can be made data flows.

const doubleIt = x => 2 * x;
const addOne = x => x + 1;

const calculation = x => addOne(doubleIt(x));

calculation(2); // 5

Avoiding shared state

App state isn't shared between objects like in object-oriented development. This is easier to explain trough what not to do.

// This example is about doing object-oriented way.

function apple(color) {
    this.color = color;
}

const apple1 = new apple('red');
const apple2 = new apple('purple');

In example above app state is shared between objects. If whole state is needed, all the objects need to be fetched. In some cases this could also have side effects on state itself. In next example how this is done without shared state.

const initialState = {
    apples: []
}

const addApple = (state, color) => Object.assign({}, state, { apples: [...state.apples, {color}] });

addApple(addApple(initialState, 'red'), 'purple');
// { apples: [ {color: 'red'}, {color: 'purple'} ] }

Avoiding mutating state

When state is updatet trough funtions, it's not straight updatet. In every change new state object is returned. This can be done like in last example.

const addApple = (state, color) => Object.assign({}, state, { apples: [...state.apples, {color}] });

Object.assign() returns new object combining last state and new properties.

Avoiding side effects

Basically same as with pure functions. No interactions outside from functions or expressions scope. This cannot be 100% avoidable because everything cannot be pure functions. In the end there will be interaction where everything is printed on screen with API which is not on your control.

Good practice is to separate these functionalities in codebase.