SlideShare a Scribd company logo
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
Functional Programming in JavaScript
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
Functional Programming in JavaScript
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!

More Related Content

What's hot (20)

Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
Scott Wlaschin
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
Load Impact
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
Learnbay Datascience
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Functional programming
Functional programmingFunctional programming
Functional programming
ijcd
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
Alexander Ioffe
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
Scott Wlaschin
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Files in java
Files in javaFiles in java
Files in java
Muthukumaran Subramanian
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
Emertxe Information Technologies Pvt Ltd
 
Flower and celery
Flower and celeryFlower and celery
Flower and celery
Rafael Roman Otero
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
Mahi Mca
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible!
Vladimir Kochetkov
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
Scott Wlaschin
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
Load Impact
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Functional programming
Functional programmingFunctional programming
Functional programming
ijcd
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
Alexander Ioffe
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
Scott Wlaschin
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
Mahi Mca
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible!
Vladimir Kochetkov
 

Similar to Functional Programming in JavaScript (20)

Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional Javascript, CVjs
Functional Javascript, CVjsFunctional Javascript, CVjs
Functional Javascript, CVjs
kaw2
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
ChengHui Weng
 
Functional programming in javascript
Functional programming in javascriptFunctional programming in javascript
Functional programming in javascript
Boris Burdiliak
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
Joseph Smith
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Troy Miles
 
Functional programming
Functional programmingFunctional programming
Functional programming
S M Asaduzzaman
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?
Ilya Sidorov
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional Javascript, CVjs
Functional Javascript, CVjsFunctional Javascript, CVjs
Functional Javascript, CVjs
kaw2
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
ChengHui Weng
 
Functional programming in javascript
Functional programming in javascriptFunctional programming in javascript
Functional programming in javascript
Boris Burdiliak
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
Joseph Smith
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Troy Miles
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?
Ilya Sidorov
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Ad

Recently uploaded (20)

Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Ad

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
  • 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
  • 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