Functional Programming in
JavaScript
Anil Wadghule
λ
Slide 2
Slide 2 text
• ?
• ?
• ?
• ?
• ?
• ?
• ?
• ?
What is Functional Programming?
Slide 3
Slide 3 text
What is Functional Programming?
• First class Functions
• Higher Order Functions
• Declarative Style
• Closures
• Recursion
• Immutability
• Pattern Matching
• Lazy Evaluation
Slide 4
Slide 4 text
Overview
• What is Functional Programming?
• Why is JavaScript Functional?
• First class functions
• Higher Order Functions
• Closure
• Applicative Functions
• Imperative vs Declarative Style
• Function Composition
Slide 5
Slide 5 text
Is JavaScript Object Oriented or Functional?
❤️ child of Self and Scheme
Slide 6
Slide 6 text
Self
• From Self, a powerful, if somewhat unusual, OO
system
• Dynamic dispatch
• Encapsulation
• Polymorphism — lots of it (weak typing!)
• Inheritance through the prototype chain
• Open recursion — through `this`
Slide 7
Slide 7 text
Scheme
• From Scheme, the most important features of
functional languages
• First class functions
• Closures
We are going to ignore OO & focus on first class functions λ
Slide 8
Slide 8 text
Bare-bones introduction to FP
Functional programming is the use of functions that
transform values into units of abstraction, subsequently used
to build software systems.
Slide 9
Slide 9 text
Object Oriented Style
Client Component
operation()
add(Component)
remove(Component)
getChild(int)
Leaf Composite
operation()
add(Component)
remove(Component)
getChild(int)
Children
operation()
Problem broken into Object Oriented Parts
Object Oriented Style
Too many objects, too many states,
mutations and hence s
Slide 13
Slide 13 text
No content
Slide 14
Slide 14 text
Functional Style
md toHTML modifyDOM
postProcess
Problem broken into Functional Parts
Slide 15
Slide 15 text
Functional Style
md toHTML postProcess modifyDOM
Functions are also composed together to form more behaviours.
visit
post
addId
genID
composed of
Slide 16
Slide 16 text
Functional Style
md toHTML postProcess modifyDOM
text html decorated html
Slide 17
Slide 17 text
Functional Style
A functional program is a machine for transforming data
Slide 18
Slide 18 text
Functions as Units of Abstraction
Make it run, make it right, make it fast
functions hide implementation details from view.
Slide 19
Slide 19 text
You have already done FP in JS
[1, 2, 3].forEach(alert);
Slide 20
Slide 20 text
You have already done FP in JS
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
Slide 21
Slide 21 text
More examples of FP in JS
That you already know
?
Slide 22
Slide 22 text
First Class Functions
• A function can be stored in variable
• A function can be stored in an array
• A function can be stored in object field
• A function can be created as needed
Slide 23
Slide 23 text
Higher Order Functions
• A function can be stored in variable
• A function can be stored in an array
• A function can be stored in object field
• A function can be created as needed
• A function can be passed to other function
• A function can be returned from a function
Slide 24
Slide 24 text
Scope
• Scope
• Global Scope
• Lexical Scope
• Dynamic Scope
• Function Scope
Lexical Scope
aVariable = "Outer";
function afun() {
var aVariable = "Middle";
return _.map([1, 2, 3], function(e) {
var aVariable = "In";
return [aVariable, e].join(' ');
});
}
// What is the value of a call to afun ? afun();
//=> ["In 1", "In 2", "In 3"]
Slide 27
Slide 27 text
Dynamic Scope
function globalThis() { return this; }
globalThis();
//=> some global object, probably Window
globalThis.call(‘mustafa');
//=> ‘mustafa’
globalThis.apply(‘zariya', [])
//=> ‘zariya’
Slide 28
Slide 28 text
Function Scope
function strangeLoop(n) {
var i;
for (i = 0; i < n; i++);
return i;
}
// strangeLoop(5)
//=> 5
// i
// ReferenceError: i is not defined
Slide 29
Slide 29 text
Closure
A closure is an inner function that has access to the
outer (enclosing) function's variables — scope chain.
The closure has three scope chains: it has access to
its own scope (variables defined between its curly
brackets), it has access to the outer function's
variables, and it has access to the global variables.
Slide 30
Slide 30 text
Closure
function showName(firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer
// function's variables, including the parameter
function makeFullName() {
return nameIntro + firstName + " " + lastName;
}
return makeFullName();
}
showName("AR", "Rahman"); // Your name is AR Rahman
Slide 31
Slide 31 text
Closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Slide 32
Slide 32 text
Applicative Functions
• Map
• Reduce
• Filter
Slide 33
Slide 33 text
Applicative Functions
Lets see code
Slide 34
Slide 34 text
Imperative Style
// Imperative style
var numbers = [1,2,3,4,5];
var doubled = [];
for(var i = 0; i < numbers.length; i++) {
var newNumber = numbers[i] * 2;
doubled.push(newNumber);
}
console.log(doubled); //=> [2,4,6,8,10]
Slide 35
Slide 35 text
Declarative Style
var numbers = [1,2,3,4,5];
var doubled = numbers.map(function(n) {
return n * 2;
});
console.log(doubled); //=> [2,4,6,8,10]
Slide 36
Slide 36 text
Composition
// Simple Compose function
var compose = function (f, g) {
return function(x) {
return f(g(x));
}
};
var f = compose(negate, square);
console.log(f(2));
Slide 37
Slide 37 text
Composition
// Simple Compose function
var compose = function (f, g) {
return function(x) {
return f.call(this, g.apply(this, arguments));
}
};
Slide 38
Slide 38 text
Composition
var compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length; i --> 0;) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
var f = compose(negate, square, mult2, add1);
console.log(f(2));
Slide 39
Slide 39 text
Composition Problem
Part of Speech Detector
Slide 40
Slide 40 text
Benefits of FP
• Simplicity
• Expressive code (Declarative code)
• Unit testing
• Easy debugging
• Concurrency (In JavaScript? - NO)
• Hot Code Deployment (In JavaScript? - NO)
Slide 41
Slide 41 text
Code examples can be found at
https://gist.github.com/anildigital/082cca114c4e72b9b31e