Functional Programming
w/ JavaScript
& React

Sebastian

Software Developer at

What is Functional Programming (FP)?

This is FP, right?

import * as _ from 'lodash';

const activeUsernames = _(users)
  .filter({ isActive: true })
  .map('username')
  .sort()
  .value();

FP actually covers
many concepts.

  • immutability / purity
  • side effects
  • composition
  • partial application
  • currying
  • monads
  • lambda
  • identity
  • more: http://git.io/fp-jargons

Some FP concepts

JavaScript, the predestined FP language?

Arrow Functions

const isMature = age => age > 17;

const getAge = user => user.profile.age;
const getAge = get('profile.age');

Functions as
first-class citizens

import { compose, map, filter } from 'lodash/fp';

const getName = user => user.name;
const isDeveloper = user => user.job === 'dev';

const getDevNames = compose(
    map(getName), filter(isDeveloper)
);

const devNames = getDevNames(users);

Multiply Example (Java)

// Curried function to multiply two integers.
Function<Integer, Function<Integer, Integer>> multiply = 
    new Function<Integer, Function<Integer, Integer>>() {
        @Override
        public Function<Integer, Integer> apply(Integer a) {
            return new Function<Integer, Integer>() {
                @Override
                public Integer apply(Integer b) {
                    return a * b;
                }
            };
        }
    };

Multiply Example (JavaScript)

// Multiply two integers.
const multiply = a => b => a * b;

Immutability

// ❌ mutability
const user = { name: 'Sandra' };
user.name = 'Fred';

// ✅ immutability
const user = { name: 'Sandra' };
const changedUser = { ...user, name: 'Fred' };

Purity

// ❌ impure function
const getStateImpure = () => window.appState.name;

// ✅ pure function
const getState = currentWin => currentWin.appState.name;

// ✅ via lodash/fp
const getState = get('appState.name');

partial application

Basic functionality:

For React:

FP JS Specification:

FP libraries

Our favorite
FP benefits

1. Composition instead of chaining

import * as _ from 'lodash';

const devNamesChained = _(users)
    .filter(isDeveloper)
    .map(getName)
    .value();

1. Composition instead of chaining

import { compose, map, filter } from 'lodash/fp';

const getDevNames = compose(
    map(getName),
    filter(isDeveloper),
);

getDevNames(users);

const getDevNamesUpper = compose(
    toUpper,
    getDevNames,
);

2. Higher-Order Functions

map(multiply(2), [1, 2, 3, 4]);
// => [2, 4, 6, 8]

withData({users: api.loadUsers}, UserListPage);
// => UserListPage called with prop "users"

3. Reusability

const getCommentsWritten = get('commentsWritten');
const isUserActive = get('isActive');

// [User] -> Number
const getTotalNrCommentsWritten = compose(
    sum,
    map(getCommentsWritten)
);

// [User] -> Number
const getAverageCommentsWritten = compose(
    mean,
    map(getCommentsWritten)
);

// [User] -> Number
const getAverageCommentsWrittenActiveUsers = compose(
    getAverageCommentsWritten,
    filter(isUserActive)
);

4. More solution,
less boilerplate

const getManagers =
    users => users.filter(user => user.isManager);
const getNamesOfManagers =
    users => getManagers(users).map(user => user.name);

// VS

const getManagers = filter(get('isManager'));
const getNamesOfManagers = compose(map(get('name')), getManagers);
// pointfree functions

5. More fun!

  • plan ahead, then write down your solution
  • powerful and standardized concepts at your disposal
  • more common understanding in your team(s)!
  • you'll become a better developer

A React Component

import { compose } from 'lodash/fp';
import { mapProps, withState } from 'recompose';
import { withAppContext } from '../../hoc/withAppContext';

// "Plain" stateless component
const ReadMoreText = (/*...*/) => {/*...*/};

// Component with state and context
export default compose(
    withAppContext,
    withState('expanded', 'setExpanded', false),
    mapProps(sanitizeText),
)(ReadMoreText);

Some more examples from
our codebase

Open your editor, Sebastian.

It's not all in
or all out.

Use FP as much as you like!

(But don't throw consistency overboard.)

Some nice awesome resources

Thank you. 💖

Questions? Comments? Opinions?

Functional Programming with JavaScript and React

By Sebastian Herrmann

Functional Programming with JavaScript and React

We highlight how we're using FP in the frontend in combination with JavaScript and React to build readable and reusable functions and components.

  • 1,897