SlideShare a Scribd company logo
<web/F><web/F>
Functional
Programming
with JavaScript
<web/F><web/F>
Agenda
1. What
a. are functions?
b. is functional programming?
2. How?
3. Why?
4. Cool Stuff
<web/F><web/F>
Ramda lodash-fp
<web/F><web/F>
Functions
A relation f from a set A to a set B is
said to be a function if every element
of set A has one and only one image
in set B.
<web/F><web/F>
Functional Programming is about using
functions as units of abstraction and
composing them to build a system.
<web/F><web/F>
Functional language or a language
facilitating functional programming is one
which supports first-class functions.
<web/F><web/F>
R.map(function (n) {
return addOne(n);
}, list);
<web/F><web/F>
R.map(function (n) {
return addOne(n);
}, list);
R.map(addOne, list);
<web/F><web/F>
$http.get('/list', function(res) {
callback(res);
});
<web/F><web/F>
$http.get('/list', function(res) {
callback(res);
});
$http.get('/list', callback);
<web/F><web/F>
Example: Searching a list
Declarative
var nameEquals = R.compose(
R.match(new RegExp(value, 'i')), R.prop('name')
);
var filtered = R.filter(nameEquals, list);
Imperative
var filtered = [], i = 0, pattern = new RegExp(value, 'i');
for (i = 0; i < list.length; i += 1) {
if (list[i].name.match(pattern)) filtered.push(list[i]);
}
<web/F><web/F>
Higher-order functions
are first-class functions, that can take as
argument or return a function.
<web/F><web/F>
Map, Reduce and Filter
are the three most important functions to
work with collections.
Do not use any of these as a loop.
<web/F><web/F>
If the input and output collections are always
going to be same length, you probably need map.
var double = (x) => x * 2;
R.map(double, [1, 2, 3]); //=> [2, 4, 6]
<web/F><web/F>
If the output collection can have lesser or equal
number of items, you probably need filter.
var isEven = (n) => n % 2 === 0;
R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
<web/F><web/F>
You probably need reduce when the input is a
collection and the output is a single value.
Reduce is also known as fold.
R.reduce(R.add, 0, [1, 2, 3]); //=> 6
<web/F><web/F>
Map, Reduce and Filter are low-level. There
are many others provided by libraries, which
can be a better fit.
<web/F><web/F>
Example: Given an array of objects, get only the
‘name’ property values in an array.
R.map(R.prop('a'), [{a: 1}, {a: 2}]);
// pluck :: k -> [{k: v}] -> v
R.pluck('a', [{a: 1}, {a: 2}]); //=> [1, 2]
<web/F><web/F>
1. Functions should be simple.
2. They should do and focus on only one thing.
3. Try writing small functions.
4. Do not mix concerns
Ref: Simple Made Easy by Rich Hickey
<web/F><web/F>
Create lot of functions
Don’t be afraid to create many small functions.
Abstract whenever two functions seems to do similar
things or some part of them are similar.
<web/F><web/F>
Open/closed principle
states "software entities (classes, modules,
functions, etc.) should be open for extension,
but closed for modification"
Ref: https://en.wikipedia.org/wiki/Open/closed_principle
<web/F><web/F>
Function Composition
var x' = f(x) ;
var x'' = g(x'); } g(f(x));
var h = R.compose(g, f); h(x);
<web/F><web/F>
Example
// notDone :: Object -> Boolean
var notDone = function (todo) {
return !todo.done;
}
var notDone =
R.compose(R.not, R.prop('done'));
<web/F><web/F>
// wordCount :: String -> Number
var wordCount = function (s) {
return s.split(' ').length;
}
var wordCount = R.compose(
R.length, R.split(' ')
);
wordCount('How many words?') //=> 3
<web/F><web/F>
Pass and return functions
If some function accepts many parameters to
perform some part of its operations try to
replace with function instead.
<web/F><web/F>
Example: Pass function
function createBuiltFile (packageName, minifier, extension, files) {
...
var name = packageName + '.' + md5(content) + '.' + extension;
...
}
function createBuiltFile (minifier, nameGenerator, files) {
...
var name = nameGenerator(content);
...
}
<web/F><web/F>
Pass functions instead of values
when you want to make a function more
generic.
<web/F><web/F>
Work with simple data structures such
as Arrays and Objects
<web/F><web/F>
Curried Functions
A function that returns a new function until it
receives all its arguments.
Originated by
Moses Schönfinkel
Developed by
Haskell Curry
<web/F><web/F>
// add :: Number -> Number -> Number
var add = R.curry(function (x, y) {
return x + y;
});
// addOne :: Number -> Number
var addOne = add(1); addOne(5); //=> 6
A curried function can be easily specialized for
your own needs.
<web/F><web/F>
fetchFromServer()
.then(JSON.parse)
.then(function(data){ return data.posts })
.then(function(posts){
return posts.map(function(post){
return post.title;
});
})
fetchFromServer()
.then(JSON.parse)
.then(R.prop('posts'))
.then(R.map(R.prop('title')))
Read: Why Curry Helps?
<web/F><web/F>
Partial Application
// propEq :: k -> v -> {k: v} -> Boolean
var idEqZero = R.propEq('id', 0);
in this example we say that R.propEq has been
partially applied.
<web/F><web/F>
● Helps you build new functions from old
one.
● Think of it as configuring a function for
your needs.
● It also makes composition easier.
<web/F><web/F>
● Declarative
● Easy to reason about
● Easy to test
Why Functional Programming Matters (by John Hughes)
<web/F><web/F>
Cool Stuff
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
Maybe(x).map(f); //=> Maybe(f(x))
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
R.map(f, Maybe(x)); //=> Maybe(f(x))
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
R.map(f, Maybe(x)); //=> Maybe(f(x))
var g = R.compose(R.map(f), Maybe);
g(x); //=> Maybe(f(x)) only if x != null
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
R.map(f, Maybe(x)); //=> Maybe(f(x))
<web/F><web/F>
Functional null checking
if (x !== null && x !== undefined) {
f(x);
}
R.map(addOne, Maybe(2)); //=> Maybe(3)
R.map(addOne, [2]) //=> [3]
<web/F><web/F>
Both Maybe and Array are Functors.
<web/F><web/F>
Functor is something that implements map.
Some Functors are Array, Maybe, Either,
Future and many others.
<web/F><web/F>
Fantasy Land Specification
https://github.com/fantasyland/fantasy-land
<web/F><web/F>
bilby.js Folktale
ramda-fantasy
<web/F><web/F>
● Start writing more functions
● Preferably pure and simple functions
● Glue your functions using higher-order
functions
● Use a functional library
● Discover!
<web/F><web/F>
References
Books
● http://functionaljavascript.com/
● https://leanpub.com/javascriptallongesix/
● https://github.com/DrBoolean/mostly-adequate-guide
Talks
● https://www.youtube.com/watch?v=AvgwKjTPMmM
● http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk/
● https://www.youtube.com/watch?v=m3svKOdZijA
<web/F><web/F>
Thank You!
Debjit Biswas
@debjitbis08
https://in.linkedin.com/in/debjitbis08

More Related Content

PPTX
Functional Programming in Javascript - IL Tech Talks week
PPTX
Functional programming in JavaScript
PDF
Functional Programming in JavaScript
PPTX
Functional Programming with JavaScript
PPT
Introduction to Functional Programming in JavaScript
PDF
Intro to Functional Programming
PPTX
Functional Programming in JavaScript by Luis Atencio
PPTX
An Introduction to Functional Programming with Javascript
Functional Programming in Javascript - IL Tech Talks week
Functional programming in JavaScript
Functional Programming in JavaScript
Functional Programming with JavaScript
Introduction to Functional Programming in JavaScript
Intro to Functional Programming
Functional Programming in JavaScript by Luis Atencio
An Introduction to Functional Programming with Javascript

What's hot (18)

PDF
Thinking in Functions: Functional Programming in Python
PDF
Introduction to functional programming (In Arabic)
PPTX
Functions in c++
PDF
Scala categorytheory
PPT
Function overloading(C++)
ODP
Clojure basics
PPT
Introduction To Functional Programming
PDF
03 function overloading
PPTX
Function overloading
PPT
Functions in C++
PPTX
Working with functions in matlab
PPT
Functions in C++
PPT
16717 functions in C++
 
PPTX
Function overloading and overriding
PPT
C++ Function
PDF
Functional programming in Python
PPT
Scala functions
PPTX
Functions in C++
Thinking in Functions: Functional Programming in Python
Introduction to functional programming (In Arabic)
Functions in c++
Scala categorytheory
Function overloading(C++)
Clojure basics
Introduction To Functional Programming
03 function overloading
Function overloading
Functions in C++
Working with functions in matlab
Functions in C++
16717 functions in C++
 
Function overloading and overriding
C++ Function
Functional programming in Python
Scala functions
Functions in C++
Ad

Similar to Functional Programming with JavaScript (20)

PPT
PHP 5.3 Part 2 - Lambda Functions & Closures
PDF
Why I Love JSX!
PDF
ES6: The Awesome Parts
PDF
Scala Validation with Functional Programming
PPT
r,rstats,r language,r packages
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
PDF
Intro to Rack
PDF
OSCON - ES6 metaprogramming unleashed
PDF
Free Based DSLs for Distributed Compute Engines
PDF
Laravel 101
KEY
URL Mapping, with and without mod_rewrite
PDF
Drupaljam xl 2019 presentation multilingualism makes better programmers
PPT
Red5 - PHUG Workshops
PDF
Modern php
KEY
JavaScript Growing Up
PPT
Php Reusing Code And Writing Functions
PPTX
Things about Functional JavaScript
PDF
R hive tutorial - udf, udaf, udtf functions
PDF
What's New In Laravel 5
PDF
Step By Step Guide For Buidling Simple Struts App
PHP 5.3 Part 2 - Lambda Functions & Closures
Why I Love JSX!
ES6: The Awesome Parts
Scala Validation with Functional Programming
r,rstats,r language,r packages
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Intro to Rack
OSCON - ES6 metaprogramming unleashed
Free Based DSLs for Distributed Compute Engines
Laravel 101
URL Mapping, with and without mod_rewrite
Drupaljam xl 2019 presentation multilingualism makes better programmers
Red5 - PHUG Workshops
Modern php
JavaScript Growing Up
Php Reusing Code And Writing Functions
Things about Functional JavaScript
R hive tutorial - udf, udaf, udtf functions
What's New In Laravel 5
Step By Step Guide For Buidling Simple Struts App
Ad

More from WebF (9)

PDF
IV - CSS architecture
PDF
III - Better angularjs
PDF
II - Angular.js app structure
PDF
2015 - Introduction to building enterprise web applications using Angular.js
PDF
II - Build Automation
PDF
Asynchronous Programming with JavaScript
PDF
Keynote - WebF 2015
PDF
I - Front-end Spectrum
PDF
ECMAScript 6
IV - CSS architecture
III - Better angularjs
II - Angular.js app structure
2015 - Introduction to building enterprise web applications using Angular.js
II - Build Automation
Asynchronous Programming with JavaScript
Keynote - WebF 2015
I - Front-end Spectrum
ECMAScript 6

Recently uploaded (20)

PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
DevOps & Developer Experience Summer BBQ
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
REPORT: Heating appliances market in Poland 2024
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
creating-agentic-ai-solutions-leveraging-aws.pdf
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
CroxyProxy Instagram Access id login.pptx
Event Presentation Google Cloud Next Extended 2025
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Belt and Road Supply Chain Finance Blockchain Solution
DevOps & Developer Experience Summer BBQ
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Transforming Manufacturing operations through Intelligent Integrations
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
REPORT: Heating appliances market in Poland 2024
madgavkar20181017ppt McKinsey Presentation.pdf
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
creating-agentic-ai-solutions-leveraging-aws.pdf
Sensors and Actuators in IoT Systems using pdf
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Weekly Chronicles - August'25 Week I
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf

Functional Programming with JavaScript