SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
f(s(a));
Functional Programming in
JavaScript
...which is what, exactly?
Functional programming is a programming paradigm that
emphasizes:
Immutable data over mutable data
Pure functions over functions with side effects
Expressions over statements
Traditional imperative/object-oriented
programming uses...
Mutable state/variables
For loops over recursion
Functions with side effects
But...What if I told you...
You don't need for loops and mutable variables
In order to avoid mutable variables, for loops, etc., functional
programmers emphasize a few key concepts
Pure functions
No side effects
Referential transparency - if it is called with the same
arguments, it will always output the same value
No data dependency between pure functions - order and
parellelization will not effect how the function runs
Recursion
Can be used in place of traditional looping
Traditional application for a loop: summing a range
function sumRange(start, end) {
var total = 0;
for (var i = start; i <= end; i++)
total += i;
return total;
}
sumRange(1, 10); // returns 55
Now, with recursion...
function sumRange(start, end, acc) {
return start > end? acc: sumRange(start + 1, end, acc + start);
}
sumRange(1, 10, 0); // also returns 55, but cooler
But wait, recursion is slow!
Not necessarily!
Tail Call Optimization
Implemented as of ES2015 ("ES6")
ES2015 compilers can optimize tail recursive functions in
strict mode
What is a tail recursive function?
A function whose main recursive call is in tail position (i.e.,
the recursive call is the last call in the function)
Higher order/ rst-class
functions
But rst, a little history...
In the 1930's, mathmatician Alonzo Church invented λ
("lambda") calculus, a model of computation based on
function abstraction, variable binding and substitution
This gave programmers a useful tool called the λ function
AKA the "anonymous function"
In JavaScript, λ functions are possible because functions are
rst-class objects. They can be:
Stored in variables
Passed to functions
Returned from functions
This allows us to use a very cool functional programming
technique called...
Currying
Currying is a functional programming technique that allows
us to transform a function of arity (the number of arguments
a function takes) N into a chain of N functions of arity 1
A currying function allows us to partially apply functions in a
very useful, exible way:
function sumThree(a, b, c) {
return a + b + c;
}
var curriedSumThree = curry(sumThree);
curriedSumThree(1)(2)(3); // 6
curriedSumThree(1,2)(3); // 6
curriedSumThree(1,2,3); // 6
curriedSumThree(1)(2,3); // 6
...how?
ES2015 makes writing a curry function pretty straightfoward
using arrow functions and the rest/spread syntax
function curry(fn) {
return function curried(...args) {
return args.length >= fn.length ?
fn.call(this, ...args) :
(...rest) => {
return curried.call(this, ...args, ...rest);
};
};
}
Source: http://www.datchley.name/currying-vs-partial-application/
Ok...but why?
It's cool
DRY - Tiny, little, exible, reusable functions
Because, with currying, we can very easily perform...
Function composition
Composition allows us to put together functions in a
compact, readible syntax that accurately re ects what we are
trying to do with our code
const add = (x, y) => x + y;
const mult = (x, y) => x * y;
const curriedAdd = curry(add);
const curriedMult = curry(mult);
const add2 = curriedAdd(2);
const mult3 = curriedMult(3);
const add2AfterMult3 = compose(add2, mult3);
add2AfterMult3(4); // returns 14
The compose function
Recursion + the rest/spread syntax allows us to express this
very concisely
const compose = (f, ...rest) =>
!rest.length? f: (...args) => f(compose(...rest)(...args));
Limitations
JavaScript is not a purely functional language. Among other
things, it lacks:
True immutability: even 'const' does not truly prevent you
from mutating data, e.g.:
Built-in function composition
Automatically curried functions
const user = {name: "johnson", number: 85};
user.name = "ochocinco"; // no error!
Some functional JS libraries
lodash.js, underscore.js, lazy.js, ramda.js: Utility libraries
that provide FP functionality, including composition and
currying, as well as the usual suspects(map, reduce, lter,
etc.). Lodash and Lazy.js are particularly interesting for
their use of lazy evaluation, a concept associated with FP,
to optimize performance
immutable.js - Provides immutable data structures
Purely functional languages
These provide enhanced functional programming
features/performance, and often force you into a functional
programming style
Haskell
Elm
There are also many "impure" functional languages that are still
"more" functional than JavaScript, including:
Scala
Clojure
Lisp
Erlang
Happy hacking!

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Le Wagon - React 101
Le Wagon - React 101Le Wagon - React 101
Le Wagon - React 101
 
React workshop
React workshopReact workshop
React workshop
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
React js
React jsReact js
React js
 
Fetch API Talk
Fetch API TalkFetch API Talk
Fetch API Talk
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
React hooks
React hooksReact hooks
React hooks
 

Similar a Functional Programming in JavaScript

Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: NotesRoberto Casadei
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in JavascriptKnoldus Inc.
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closuresmelechi
 

Similar a Functional Programming in JavaScript (20)

Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Inline function
Inline functionInline function
Inline function
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
 
Java 8
Java 8Java 8
Java 8
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 

Último

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 

Último (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 

Functional Programming in JavaScript

  • 2. ...which is what, exactly? Functional programming is a programming paradigm that emphasizes: Immutable data over mutable data Pure functions over functions with side effects Expressions over statements
  • 3. Traditional imperative/object-oriented programming uses... Mutable state/variables For loops over recursion Functions with side effects
  • 4. But...What if I told you... You don't need for loops and mutable variables
  • 5.
  • 6. In order to avoid mutable variables, for loops, etc., functional programmers emphasize a few key concepts
  • 7. Pure functions No side effects Referential transparency - if it is called with the same arguments, it will always output the same value No data dependency between pure functions - order and parellelization will not effect how the function runs
  • 8. Recursion Can be used in place of traditional looping Traditional application for a loop: summing a range function sumRange(start, end) { var total = 0; for (var i = start; i <= end; i++) total += i; return total; } sumRange(1, 10); // returns 55
  • 9. Now, with recursion... function sumRange(start, end, acc) { return start > end? acc: sumRange(start + 1, end, acc + start); } sumRange(1, 10, 0); // also returns 55, but cooler
  • 10. But wait, recursion is slow! Not necessarily!
  • 11. Tail Call Optimization Implemented as of ES2015 ("ES6") ES2015 compilers can optimize tail recursive functions in strict mode What is a tail recursive function? A function whose main recursive call is in tail position (i.e., the recursive call is the last call in the function)
  • 13. But rst, a little history... In the 1930's, mathmatician Alonzo Church invented λ ("lambda") calculus, a model of computation based on function abstraction, variable binding and substitution This gave programmers a useful tool called the λ function AKA the "anonymous function"
  • 14. In JavaScript, λ functions are possible because functions are rst-class objects. They can be: Stored in variables Passed to functions Returned from functions This allows us to use a very cool functional programming technique called...
  • 16. Currying is a functional programming technique that allows us to transform a function of arity (the number of arguments a function takes) N into a chain of N functions of arity 1 A currying function allows us to partially apply functions in a very useful, exible way: function sumThree(a, b, c) { return a + b + c; } var curriedSumThree = curry(sumThree); curriedSumThree(1)(2)(3); // 6 curriedSumThree(1,2)(3); // 6 curriedSumThree(1,2,3); // 6 curriedSumThree(1)(2,3); // 6
  • 17. ...how? ES2015 makes writing a curry function pretty straightfoward using arrow functions and the rest/spread syntax function curry(fn) { return function curried(...args) { return args.length >= fn.length ? fn.call(this, ...args) : (...rest) => { return curried.call(this, ...args, ...rest); }; }; } Source: http://www.datchley.name/currying-vs-partial-application/
  • 18. Ok...but why? It's cool DRY - Tiny, little, exible, reusable functions Because, with currying, we can very easily perform...
  • 19. Function composition Composition allows us to put together functions in a compact, readible syntax that accurately re ects what we are trying to do with our code const add = (x, y) => x + y; const mult = (x, y) => x * y; const curriedAdd = curry(add); const curriedMult = curry(mult); const add2 = curriedAdd(2); const mult3 = curriedMult(3); const add2AfterMult3 = compose(add2, mult3); add2AfterMult3(4); // returns 14
  • 20.
  • 21. The compose function Recursion + the rest/spread syntax allows us to express this very concisely const compose = (f, ...rest) => !rest.length? f: (...args) => f(compose(...rest)(...args));
  • 22. Limitations JavaScript is not a purely functional language. Among other things, it lacks: True immutability: even 'const' does not truly prevent you from mutating data, e.g.: Built-in function composition Automatically curried functions const user = {name: "johnson", number: 85}; user.name = "ochocinco"; // no error!
  • 23. Some functional JS libraries lodash.js, underscore.js, lazy.js, ramda.js: Utility libraries that provide FP functionality, including composition and currying, as well as the usual suspects(map, reduce, lter, etc.). Lodash and Lazy.js are particularly interesting for their use of lazy evaluation, a concept associated with FP, to optimize performance immutable.js - Provides immutable data structures
  • 24. Purely functional languages These provide enhanced functional programming features/performance, and often force you into a functional programming style Haskell Elm There are also many "impure" functional languages that are still "more" functional than JavaScript, including: Scala Clojure Lisp Erlang