SlideShare a Scribd company logo
Functional Programming in JS (light intro)
Nikos Kalogridis
@nikoskalogridis
FP HISTORY
Based on λ-calculus (1930)
Lisp (late 1950's)
...Haskel (1987)
...Javascript (1995)
Clojure (2007), Elm (2012)
CONCEPTS
First class / higher order functions
Declarative instead of imperative style
Function composition
Currying / Partial Application
Recursive functions / Tail recursion
Pure Functions
Immutablility
FIRST CLASS FUNCTIONS
A programming language that treats functions as
first-class citizens
(errrr.....)
functions can take as arguments other functions
functions can be returned by functions
functions can be assigned to a variable
HIGHER ORDER FUNCTIONS (HOF)
A function that takes as an argument another
function
A function that returns another function
or does both
EXAMPLE (HOF)
var myArray = [1, 2, 3, 4, 5];
function times(x) {
return function (y) {
return x * y;
}
}
myArray.map(times(2));
// -> [2, 4, 6, 8, 10]
MAP
Returns a new array with the result of applying a
function on each element of the array
var myArray = [1, 2, 3, 4, 5];
myArray.map(function (value) {
return value + 1;
});
// -> [2, 3, 4, 5, 6]
FILTER
Returns a new array with all elements that pass the
test implemented by the provided function
var myArray = [1, 2, 3, 4, 5];
myArray.filter(function (value) {
return value < 4;
});
// -> [1, 2, 3]
REDUCE
Reduces the elements to a single value applying a
function to each of them
var myArray = [1, 2, 3, 4, 5];
myArray.reduce(function (acc, value) {
return acc + value;
}, 0);
// -> 15
IMPERATIVE VS DECLARATIVE
Given an array of numbers return the numbers that
are less than 4 and add to each of those 10
var myArray = [1, 2, 3, 4, 5];
var result = [];
var i = 0;
for (i; i < myArray.length; i += 1) {
if (myArray[i] < 4) {
result.push(myArray[i] + 10);
}
}
var myArray = [1, 2, 3, 4, 5];
var result = myArray
.filter((value) => value < 4)
.map((value) => value + 10);
FUNCTION COMPOSITION
import {filter, flow} from 'lodash/fp';
const users = [ {name: 'Mary', age: 46, active: true},
{name: 'John', age: 40, active: true},
{name: 'Helen', age: 30, active: true},
{name: 'Mike', age: 25, active: false} ];
const eligibleMiddleAgeGroup = flow(
filter('active'), // (user) => user.active
filter((user) => user.age >= 45 && user.age < 65))
);
eligibleMiddleAgeGroup(users)
// -> [{name: 'Mary', age: 46, active: true}]
CURRYING / PARTIAL APPLICATION
function times(x) {
return function (y) {
return x * y;
}
}
function times(x, y) {
if (y === undefined) {
return function (y) {
return x * y;
}
}
return x * y;
}
RECURSIVE FUNCTIONS / TAIL RECURSION
function countdown(value) {
if (value < 0) {
return;
}
console.log(value);
return countdown(value - 1);
}
PURE FUNCTION
its return value is affected only by its passed
parameters
and has no side effects
PURE VS IMPURE
var a = 10;
function impure(x) {
return x + a;
}
function pure(x, y) {
return x + y;
}
SIDE EFFECTS
var a = 0;
function impure(x) {
a = x + a;
}
function impure(x) {
console.log(x);
return x + 1;
}
IMMUTABLILITY
const user = {name: 'Niks', age: 40, gender: 'male'};
user.age = 41; // mutation
// avoiding mutation
const updatedUser = Object.assign({}, user, {age: 41});
FUNCTIONAL PROGRAMMING STYLE
don't
Use loops
Mutate objects/arrays
Don't do side effects
do
Use tail recursion
Create new instancies when modifying
objects/arrays
Isolate side effects outside business logic
PROS
Decouple data from operations
Easier testing
Easier to reason about
Easier to maintain/fix
No mutation allows for easier concurrency
Industry seems to move to it
CONS
Needs more memory
Runs slower (on dumb compilers)
OOP programmers find it difficult to adapt
Scares non CS people of with maths (even CS
people are scared...)
Requires rewiring your brain
Javascript allows you to use any style
USEFUL LINKS
Many more to fit this slide...
Professor Frisby's guide to functional programming
Functional Javascript (by Michael Fogus)
Javascript: The Good Parts (by Douglas Crockford)
Functional-lite Javascript video course (by Kyle
Simpson)
LoDash
Ramda
lazy.js
QUESTIONS
THANK YOU

More Related Content

What's hot (20)

PPTX
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
PPTX
Functional programming in JavaScript
Joseph Smith
 
PPTX
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
PPTX
Functional Programming with JavaScript
Aung Baw
 
PPTX
Function overloading
Selvin Josy Bai Somu
 
PPT
Introduction to Functional Programming in JavaScript
tmont
 
PPTX
07. Virtual Functions
Haresh Jaiswal
 
PPT
Scala functions
Knoldus Inc.
 
PPT
Function overloading(C++)
Ritika Sharma
 
PDF
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
PPTX
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
PPT
3 Function Overloading
Praveen M Jigajinni
 
PDF
Functions in C++
Pranali Chaudhari
 
DOCX
Virtual function
harman kaur
 
PPTX
Abstract Base Class and Polymorphism in C++
Liju Thomas
 
PDF
Introduction to functional programming
Konrad Szydlo
 
PDF
03 function overloading
Jasleen Kaur (Chandigarh University)
 
PPT
pointers, virtual functions and polymorphisms in c++ || in cpp
gourav kottawar
 
PPT
An Overview Of Python With Functional Programming
Adam Getchell
 
PPTX
Function overloading in c++
Learn By Watch
 
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Functional programming in JavaScript
Joseph Smith
 
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Functional Programming with JavaScript
Aung Baw
 
Function overloading
Selvin Josy Bai Somu
 
Introduction to Functional Programming in JavaScript
tmont
 
07. Virtual Functions
Haresh Jaiswal
 
Scala functions
Knoldus Inc.
 
Function overloading(C++)
Ritika Sharma
 
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
3 Function Overloading
Praveen M Jigajinni
 
Functions in C++
Pranali Chaudhari
 
Virtual function
harman kaur
 
Abstract Base Class and Polymorphism in C++
Liju Thomas
 
Introduction to functional programming
Konrad Szydlo
 
03 function overloading
Jasleen Kaur (Chandigarh University)
 
pointers, virtual functions and polymorphisms in c++ || in cpp
gourav kottawar
 
An Overview Of Python With Functional Programming
Adam Getchell
 
Function overloading in c++
Learn By Watch
 

Similar to Functional programing in Javascript (lite intro) (20)

PPTX
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
PDF
379008-rc217-functionalprogramming
Luis Atencio
 
ODP
Functional programming
S M Asaduzzaman
 
PPTX
Functional programming in javascript
Boris Burdiliak
 
PDF
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
PDF
Functional programming 101
Maneesh Chaturvedi
 
PDF
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
PPTX
Thinking Functionally with JavaScript
Luis Atencio
 
PDF
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
PPTX
Why Functional Programming So Hard?
Ilya Sidorov
 
PPTX
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
reactima
 
PPT
25-functions.ppt
JyothiAmpally
 
PPTX
Functional Programming In JS
Damian Łabas
 
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
PPTX
Functionnal programming
AndryRajohnson
 
PDF
Functional Programming in JavaScript
Troy Miles
 
PPTX
Declarative JavaScript concepts and implemetation
Om Shankar
 
PPTX
A Skeptics guide to functional style javascript
jonathanfmills
 
PDF
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
PPTX
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
379008-rc217-functionalprogramming
Luis Atencio
 
Functional programming
S M Asaduzzaman
 
Functional programming in javascript
Boris Burdiliak
 
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional programming 101
Maneesh Chaturvedi
 
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
Thinking Functionally with JavaScript
Luis Atencio
 
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Why Functional Programming So Hard?
Ilya Sidorov
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
reactima
 
25-functions.ppt
JyothiAmpally
 
Functional Programming In JS
Damian Łabas
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Functionnal programming
AndryRajohnson
 
Functional Programming in JavaScript
Troy Miles
 
Declarative JavaScript concepts and implemetation
Om Shankar
 
A Skeptics guide to functional style javascript
jonathanfmills
 
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Ad

Recently uploaded (20)

PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PDF
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PDF
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
Cerebraix Technologies
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPTX
internet básico presentacion es una red global
70965857
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
Orchestrating things in Angular application
Peter Abraham
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
Cerebraix Technologies
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
internet básico presentacion es una red global
70965857
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
Ad

Functional programing in Javascript (lite intro)

  • 1. Functional Programming in JS (light intro) Nikos Kalogridis @nikoskalogridis
  • 2. FP HISTORY Based on λ-calculus (1930) Lisp (late 1950's) ...Haskel (1987) ...Javascript (1995) Clojure (2007), Elm (2012)
  • 3. CONCEPTS First class / higher order functions Declarative instead of imperative style Function composition Currying / Partial Application Recursive functions / Tail recursion Pure Functions Immutablility
  • 4. FIRST CLASS FUNCTIONS A programming language that treats functions as first-class citizens (errrr.....) functions can take as arguments other functions functions can be returned by functions functions can be assigned to a variable
  • 5. HIGHER ORDER FUNCTIONS (HOF) A function that takes as an argument another function A function that returns another function or does both
  • 6. EXAMPLE (HOF) var myArray = [1, 2, 3, 4, 5]; function times(x) { return function (y) { return x * y; } } myArray.map(times(2)); // -> [2, 4, 6, 8, 10]
  • 7. MAP Returns a new array with the result of applying a function on each element of the array var myArray = [1, 2, 3, 4, 5]; myArray.map(function (value) { return value + 1; }); // -> [2, 3, 4, 5, 6]
  • 8. FILTER Returns a new array with all elements that pass the test implemented by the provided function var myArray = [1, 2, 3, 4, 5]; myArray.filter(function (value) { return value < 4; }); // -> [1, 2, 3]
  • 9. REDUCE Reduces the elements to a single value applying a function to each of them var myArray = [1, 2, 3, 4, 5]; myArray.reduce(function (acc, value) { return acc + value; }, 0); // -> 15
  • 10. IMPERATIVE VS DECLARATIVE Given an array of numbers return the numbers that are less than 4 and add to each of those 10 var myArray = [1, 2, 3, 4, 5]; var result = []; var i = 0; for (i; i < myArray.length; i += 1) { if (myArray[i] < 4) { result.push(myArray[i] + 10); } } var myArray = [1, 2, 3, 4, 5]; var result = myArray .filter((value) => value < 4) .map((value) => value + 10);
  • 11. FUNCTION COMPOSITION import {filter, flow} from 'lodash/fp'; const users = [ {name: 'Mary', age: 46, active: true}, {name: 'John', age: 40, active: true}, {name: 'Helen', age: 30, active: true}, {name: 'Mike', age: 25, active: false} ]; const eligibleMiddleAgeGroup = flow( filter('active'), // (user) => user.active filter((user) => user.age >= 45 && user.age < 65)) ); eligibleMiddleAgeGroup(users) // -> [{name: 'Mary', age: 46, active: true}]
  • 12. CURRYING / PARTIAL APPLICATION function times(x) { return function (y) { return x * y; } } function times(x, y) { if (y === undefined) { return function (y) { return x * y; } } return x * y; }
  • 13. RECURSIVE FUNCTIONS / TAIL RECURSION function countdown(value) { if (value < 0) { return; } console.log(value); return countdown(value - 1); }
  • 14. PURE FUNCTION its return value is affected only by its passed parameters and has no side effects
  • 15. PURE VS IMPURE var a = 10; function impure(x) { return x + a; } function pure(x, y) { return x + y; }
  • 16. SIDE EFFECTS var a = 0; function impure(x) { a = x + a; } function impure(x) { console.log(x); return x + 1; }
  • 17. IMMUTABLILITY const user = {name: 'Niks', age: 40, gender: 'male'}; user.age = 41; // mutation // avoiding mutation const updatedUser = Object.assign({}, user, {age: 41});
  • 18. FUNCTIONAL PROGRAMMING STYLE don't Use loops Mutate objects/arrays Don't do side effects do Use tail recursion Create new instancies when modifying objects/arrays Isolate side effects outside business logic
  • 19. PROS Decouple data from operations Easier testing Easier to reason about Easier to maintain/fix No mutation allows for easier concurrency Industry seems to move to it
  • 20. CONS Needs more memory Runs slower (on dumb compilers) OOP programmers find it difficult to adapt Scares non CS people of with maths (even CS people are scared...) Requires rewiring your brain Javascript allows you to use any style
  • 21. USEFUL LINKS Many more to fit this slide... Professor Frisby's guide to functional programming Functional Javascript (by Michael Fogus) Javascript: The Good Parts (by Douglas Crockford) Functional-lite Javascript video course (by Kyle Simpson) LoDash Ramda lazy.js