Functional JavaScript

That Conference 2018

John Ptacek

Skyline Technologies

@jptacek

Talk

Functional Programming Concepts

ES6 features

About Me

John Ptacek

Skyline Technologies/Vice Principal Consultant

@jptacek

jptacek@skylinetechnologies.com

https://jptacek.com

Functional JavaScript

JavaScript

JavaScript allow for multiple programming styles

  • Object Oriented
  • Procedural
  • Functional

Developers need to program functionally, language doesn’t provide

Functional Programming

A programming PARADIGM in which computation is the application of functions that supports and encourages the functional style

Functional languages support the style

Lisp, Haskell, Erlang

Functional Programming

Think math

f(x) = x+1

f(3) = 4

cos(π) = -1

Functional Programming

Not for all the things

It is a different paradigm

  • Imperative - Do this, then that
  • Object Oriented - Methods change state

Good for some operations and not so much for others

What is good for

Stateless (FAAS)

Algorithms

Data Analysis and Transformation

Testing

What is NOT good for

State Machine

Speed

Learning Curve

Functional Programming

Evaluation of mathematical functions

Avoid mutable state

Referential transparency

Avoid side effects

Reusable functions over reusable objects

Function composition over object composition

Why Functional

Less Bugs

Less Complexity

More Readable Code

Functional Programming

Uses functions!

Lambda Calculus

Elements of Functional Programming

First class functions - Stores in variables, passed to functions, created within function, returned from functions

Higher Order Functions - Functions that accept functions as arguments and return functions

No side effects - Only return a result. Anything else is a side effect

Referential Transparency - For a given set of arguments, same code should always output same value

Elements of Functional Programming

Immutability - Inability for variables to change their values once created. Another way to say, all the things are constant

Currying - Ability of a function to return a new function with some params

Tail Call Optimization - Ability to avoid allocating new stack frame

λ-calculus (lambda calculus)

Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any Turing machine. - Wikipedia

https://medium.com/@Sudhagar/an-informal-introduction-to-lambda-calculus-51c637f35f7d

Anonymous functions

Unary - Functions take on argument, return one value

Lambda x . x+2

X is input x+2 is return value

f(x) = x+2

Functional Programming

Functions are “first class citizens”

  • Functions can have properties/methods
  • Assigned to variables
  • Pass as arguments

Functions are called by references using ()

Function as objects example - 01

let myFunc = function() {
let y = 3;
console.log(`myFunc ${y}`);
}

// We execute myFunc by throwing parens around it
// myFunc();

// anotherFunc takes a function as a passed in parameter and then executes
// it.
let anotherFunc= function(passInFunc) {
console.log('anotherFunc');
passInFunc();
}

anotherFunc(myFunc);


// myVarFun takes a parameter in function list and displays it
let myVarFunc = function(valToDisplay) {
console.log(`myVarFunc ${valToDisplay}`);
}

myVarFunc(4);
anotherFunc(myVarFunc); // This errors out

// We need to use an anonymous function if we want to pass parameters
anotherFunc(function(){myVarFunc(7)});

Functional Programming

Functions have inner embedded functions of any depth

Arguments and variables of outer functions available to inner functions

  • Closure
  • Enclose scope to function

Elements - Pure Functions

Returns the same output for the same input, every time. EVERY TIME

Only one result for any given set of arguments

Don’t rely on the state of the code they’re called from

Don’t create side effects that alter variables outside the function

Elements - Pure Functions

function pure(x,y) {

Return x+y;

}

const x =1;

function impure(y) {

Return x+y;

}

Elements - Pure Functions - Side Effects

Changing variable, property, data structure globally

Changing original value of function argument

Processing user input

Querying HTML document, browser cookies, databases, etc

Logging(console.log) or any DOM manipulation.

Elements - Pure Functions

function getLogNameImpure() {

let currentDate = new Date();
return `${currentDate.getFullYear()}log.txt`;

}

function getLogNamePure(currentDate) {
return `${currentDate.getFullYear()}log.txt`;

}

Elements - Pure Functions

Results easy to reproduce and test

Can be called in parallel without altering results (no race conditions)

Memoization - Fancy word for caching

Elements - Higher Order functions

Functions that operate on other functions, either by taking them as arguments or by returning them

You already know them as callbacks

The magic of functional programing

Functions can be template functions

ES5 - Map, Filter, Reduce

Higher Order functions part of ECMASCRIPT 5 standard

Take lists and transform into NEW lists

ES5 - Map

Used to apply a function on every element in an array. A new array is returned.

A for loop replacement for transforming values

Does not mutate state on existing array

ES5 - Map

let newArr = oldArr.map((value, index, array) => {
// return element to new Array
});

ES5 - Filter

Used to apply a function on every element in an array

Syntax similar to Map, but return value needs to be true or false

ES5 - Filter

let newArr = oldArr.map((value, index, array) => {
// return true or false

});

ES5 - Reduce

Operates on all values in array to create a single value

Syntax similar to Map and Filter, but we include an accumulator variable

ES5 - Reduce

let sumValue = oldArr.reduce((acc,value, index, array) => {
// return operation

},0);

Immutability

Objects don't change state

let result = [1,2,3]

.map (x=> x+1) // [2,3,4]

.filter (x => x>2); // [3,4]

First two arrays used for calculation, get collected but never changed

Currying

Reduces functions of multiple arguments to functions of one argument

Named after Haskell Curry

Partial Application

Essentially, pass all arguments and get result or pass subset and get a function awaiting input

Recursion

Functional Purists are going to yell at you about loops

Recursion has action and stop

Tail Call Optimization in ES6

Questions?

John Ptacek

@jptacek

Thank You!

Functional JavaScript - That Conference 2018 - Google Slides