Functional Programming

in JavaScript

Daniel Mocan

Software Developer @ Fortech

Meetup organizer @ JSHeroes

Twitter: @danielsmocan

Content

intro

functions in javascript

pure functions

immutability

high order functions

partial application & currying

composition

decorators

What is Functional Programming?

Functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. (Wikipedia)

What is Functional Programming?

Functional Programming is part of the declarative paradigme.

Declarative Programming

It focuses on telling the computer what it wants instead of how to compute.

Imperative Programming

It describes how to perform an action.

How ( Imperative )

let users = [
  { firstName: "Vasile", lastName: "Popescu" },
  { firstName: "Ion", lastName: "Ionescu" },
  { firstName: "Dani", lastName: "Mocanu" }
]

for ( var i = 0; i < users.length; i++) {
  users[i].fullName = `${ users[i].firstName } ${ users[i].lastName }`;
}
console.log( users );

What ( Declarative )

const users = [
  { firstName: "Vasile", lastName: "Popescu" },
  { firstName: "Ion", lastName: "Ionescu" },
  { firstName: "Dani", lastName: "Mocanu" }
]
const addFullName = user => Object.assign(
    {}, user, { fullName: `${ user.firstName } ${ user.lastName }` } 
);
const modifiedUsers = users.map( addFullName );
console.log( modifiedUsers );

Exercises

Functions in JavaScript

Functions are the cornerstones of any functional programming language. Functions in JavaScript are first class citizen.

Functions is JavaScript can be:

variables

elements of an array

keys on an object

returned from a function

passed as params

Functions in JavaScript

//They can be variables
const sum = function sum( a, b ) {
  return a + b;
}

//functions that return functions
function sum2( a ) {
  return function( b ) {
    return a + b; 
  }
}

//or written more clean like this
const sum2 = ( a ) => ( b ) => a + b;

//passed as parameters
const sumOfThree = ( a , b, c, sum ) => sum( a, b ) + c;

//part of an array
const arrayOfFunctions = [ sum, sum2, sumOfThree ];

//part of an object
const person = {
  name: "Vasile",
  getAge: () => 23,
}

Pure Functions

Pure functions are

functions that have consistent results

avoid shared state

no side effects

return data

Pure Functions

let points = 5;
const addPoints = ( a ) => { points += b };
addPoints(3);

Impure function

const totalPoints = 5;
const addPoints = ( totalPoints, points ) => totalPoints + points;
const newTotalPoints = addPoints( totalPoints, 5 );

Pure function

Pure Functions

Benefits of using pure functions

are easy to test

easier to track bugs

reduces new bugs

Exercises

Immutability

Immutability is a core concept in functional programming.

An immutable object is an object that can not be modified after its creation.

You can't screw up what you can't change

JavaScript does not have immutable data structure by default.

Immutability



const name = "Vasile";
name = "Ion"; // Uncaught TypeError: Assignment to constant variable...

const person = { 
  name: "Vasile",
  age: 89,
  position: "Junior Cobol Developer"
};

person.name = "Ion"; // works fine;

const declaration in JS

You can create immutable object in JS by using Object.freeze

Exercises

High Order Functions

HOC are functions that

receive a functions as a parameter

it returns a function

/* Receives a function as a param */
  const apply = ( func, value ) => func( value );
  
  /* Returns a function */ 
  const addOne = value => value + 1;
  
  const total = apply( addOne, 4 );
  console.log( total );

Exercises

Partial Application and Currying

Partial Application is supplying less parameters than required

function partialApplication( f, a ) {
    return function( b ) {
        return f( a, b )
    }
}

const sum = ( a, b ) => a + b;
const addFive = partialApplication( sum, 5 );
addFive( 6 ); // 11

Partial Application and Currying

Currying is converting a function that accepts multiple params in a series of functions that accept only one

const add = ( a ) => ( b ) => ( c ) => a + b + c;
add( 1 )( 2 )( 3 ); // 6

No Exercises :)

Function Composition

Function composition is combining functions to create a new function

const increment = a => a + 1;
const double = a => a + a;
const incrementAndDouble = a => double( increment( a ) );

Function Composition

Compose

const compose = ( f, g ) => x => f( g( x ) );
const incrementAndDouble = compose( increment, double );

Function Composition

Generic Compose

const compose = ( func, ...rest ) => rest.length ? 
                x => func( compose( ...rest ) ( x ) ) : 
                func;
const square = a => a * a;
const doubleIncrementAndSquare = compose( square, increment, double );

Exercises

Function Decorators

Function decorators are function that receive a function as a parameter and returns a modified version of it.

function authenticateBefore( fn ) {
    return function( ...args ) {
        if ( user.isAuthenticated ) {
            return fn( ...args );
        }
    }
}

Exercises

Summary

What vs How

side effects

the status of functions in JavaScript

the importance of immutability

avoid the shared state

the benefits of pure functions

the power of combining functions

What did you found useful / interesting?

Feedback

Multumesc

Functional Programming (Workshop)

By Daniel Mocan

Functional Programming (Workshop)

Fortech Internal Workshop

  • 183