SlideShare a Scribd company logo
Fuel Up
JavaScript (with)
Functional
Programming
FAYA:80
About Me
 A passionate programmer finding my way around Functional
Programming…
 Work at UST Global
 I occasionally blog at http://stoi.wordpress.com
 Author of YieldJS & SlangJS
 I recently co-authored a book with my colleague, friend and
mentor called “.NET Design Patterns” by PACKT
Publishing
History
Logic
Computation
Category
Theory
David
Hilbert
Kurt
Godel
Gentzen
Alonzo
Church
Alan
Turing
Haskell
Curry
William
Howard
Leap ( A projectile at 90 degrees)
Computing Paradigm
 <Functional>
 Imperative Paradigms with OOP
 Domain Driven Design
 Design Patterns
 Object Functional
 Reactive Programming
 <Functional> Reactive
Computing Platform
 Single Core
 Multi-core
 Many-core
 Clusters/Load-Balancers
 Hypervisors
 Virtual Machines
 Cloud 100 Years
JS Evolution (A snap-shot)
Client Side
 DHTML/Dom Manipulation
 XMLHTTP/AJAX
 jQuery (John Resig)
 Web Frameworks
 YUI, JQuery UI, Backbone, Knockout,
Angular, Bootstrap etc.
 Libraries
 RxJs, Underscore, Prototype, Immutable,
Redux, Lodash, Ramda etc.
 Trans-compilers
 Coffescript, Typescript, Flow etc.
 Mobile Application Platforms
 Hybrid – Sencha/Cordova based
Server Side
 Node.js (Ryan Dahl)
 Node Modules
 JS Libraries
Being Functional
Algorithm composition to be dealt on the same lines
as mathematical function evaluations
 Referential Transparency
 Predictable
 Transparent
 Declarative
 Composable
 Modular
Lambda (λ) calculus
Alonzo Church Definition
Lambda calculus (also written as λ-calculus) is a
formal system in mathematical logic for expressing
computation based on function abstraction and
application using variable binding and substitution
var AddOperation = (x, y) => x + y;
Lambda Abstraction : λx.x+y [f(x,y) = x + y]
Variables : x & y
Lambda Term : x + y
Simplifications
1. Anonymous functions
2. Uses functions of a single input
Lambda (λ) calculus - Continued
 The following three rules give an inductive definition that can be applied
to build all syntactically valid lambda terms:
 A variable x, is itself a valid lambda term
 If t is a lambda term, and x is a variable, then (λx.t) is a lambda term (called a
lambda abstraction);
 if t and s are lambda terms, then (ts) is a lambda term (called an application)
Lambda (λ) calculus - Consequences
λ
Referential
Transparency
Anonymous
Functions
First-Class
Functions
Higher-Order
Functions
Closures
Currying &
Partial
Application
Recursion
Memoization
Referential Transparency
Code Motivation
Now since state of i is not guaranteed mutation-free
AddOneRO (x) <> AddOneRO (y)
if x = y, this further implies
AddOneRO (x) - AddOneRO (x) <> 0
thus invalidating the fundamental mathematical
identity
x – x = 0
Closures
Code Motivation
Now since state of i is not guaranteed mutation-free
AddOneRO (x) <> AddOneRO (y)
if x = y, this further implies
AddOneRO (x) - AddOneRO (x) <> 0
thus invalidating the fundamental mathematical
identity
x – x = 0
Currying Concept
 Transforms a function that takes
multiple arguments into a
chain of functions each with a
singleargument. a
f (a,b,c)
a
b
c
Currying Implementation – ES5
Augmenting Types Closures Apply Invocation
Currying Implementation – ES6
Closures Apply Invocation
Partial Application – ES6
Transforms a function that take multiple
arguments into afunction that accepts a
fixed number of arguments,
which in turn yields yet another
function that accepts the
remaining arguments.
Recursion
 Recursions are leveraged in functional
programming to accomplish
iteration/looping.
 Recursive functions invoke
themselves, performing an operation
repeatedly till the base case is reached
 Recursion typically involves adding
stack frames to the call stack, thus
growing the stack
 You can run out of stack space during
deep recursions
Tail-Call Optimization
 In this case, no state, except for the
calling function's address, needs to be
saved either on the stack or on the
heap
 Call stack frame for fIterator is reused
for storage of the intermediate results.
 Another thing to note is the addition
of an accumulator argument (product
in this case)
Monads
 Monad is a design pattern used to
describe computations as a series of
steps.
 Monads wrap types giving them
additional behavior like the automatic
propagation of empty value (Maybe
monad) or simplifying asynchronous
code (Continuation monad).
 Identity Monad
 Wraps Itself
 Maybe Monad
 It can represent the absence of any
value
 List Monad
 Represents a lazily computed list of
values
 Continuation monad
 Binds the context
JS Language Features That Aid
Functional Programming
ES5
 First-class functions
 Function objects
 Lexical scoping
 Function scope
 Closures
 Prototypal Inheritance
 Augmenting Types
 Function Invocation
 Controlling context (with Apply & Call)
 Array Methods
 map, reduce, filter
ES6
 Arrow Functions
 function*
 yield, yield* expressions
 Map object
Scenario1
 How do you add Exception Handling
to your code-base without
extensive code-change?
Scenario2
 You tend to write algorithms that
operate more often on a sequence of
items than on a single item.
 More likely, you’ll perform several
transformations between the source
collection and the ultimate result.
Scenario2 – Solution A
 Iterating the collection once for every
transformation (n iterations for n
transformations)
 Increases the execution time for
algorithms with many transformations
 Increases the application’s memory
footprint as it creates interim
collections for very transformation
END
Output List -> Interim List2
Transformation2 (Square)
Interim List2 -> [1, 9, 25]
Transformation1 (Filter Odds)
Interim List1 -> [1, 3, 5]
START
Input List -> [1, 2, 3, 4, 5]
Scenario2 – Solution B
 Create one method that processes
every transformation (1 iteration for n
transformations)
 Final Collection is produced in one
iteration. This improves performance
 Lowers the application’s memory
footprint as it doesn’t create interim
collections for every transformation
 Sacrifices Reusability (of individual
transformations)
END
Output List -> Interim List1
Transformation1 (Filter Odds + Square)
Interim List1 -> [1, 9, 25]
START
Input List -> [1, 2, 3, 4, 5]
Scenario2 – Solution C
 Iterators
 Enables you to create methods that operate on a sequence
 Iterator methods do not need to allocate storage for the entire sequence of
elements
 Process and return each element as it is requested (Deferred Execution)
Step in
 A JavaScript library for creating
Iterators, Generators and Continuation
methods for Arrays.
 The Iterator would be a method
getIterator() that augments the Array
data type and would have the
following interfaces:
 moveNext (method)
 current (property)
 reset (method)
ITERATOR
• Input List [1,2,3,4,5]
MoveNEXT
• 1 <- Square(FilterODD(1))-> OutputList [1]
MoveNEXT
• 2 <- FilterODD(2)-> MoveNEXT
• 3 <- Square(FilterODD(3))-> OutputList [1,9]
MoveNEXT
• 4 <- FilterODD(4)-> MoveNEXT
• 5 <- Square(FilterODD(5))-> OutputList [1,9,25]
ES6 – Generators & Iterators
 function*
 The function* declaration (function
keyword followed by an asterisk)
defines a generator function, which
returns a Generator object.
 Generator Object
 The Generator object is returned by a
generator function and it conforms to
both the iterable protocol and the
iterator protocol.
 Generators are functions which can be
exited and later re-entered. Their
context (variable bindings) will be
saved across re-entrances.
Concluding
 The proof is in the pudding!!!

More Related Content

What's hot (20)

ODP
Pattern Matching - at a glance
Knoldus Inc.
 
PDF
A Survey of Concurrency Constructs
Ted Leung
 
PDF
Getting Started With Scala
Xebia IT Architects
 
PPTX
Java 103 intro to java data structures
agorolabs
 
PDF
camel-scala.pdf
Hiroshi Ono
 
PPT
1 list datastructures
Nguync91368
 
PPTX
Introduction To R Language
Gaurang Dobariya
 
PDF
Functional Programming in Scala: Notes
Roberto Casadei
 
PPTX
Core java concepts
laratechnologies
 
PDF
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PPTX
Introduction to matlab
Khulna University
 
PPT
Matlab1
guest8ba004
 
PPTX
Arrays in Data Structure and Algorithm
KristinaBorooah
 
PPTX
stacks and queues for public
iqbalphy1
 
PDF
C++ Standard Template Library
Ilio Catallo
 
PPT
Scala
Zhiwen Guo
 
ODP
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
ODP
Functional programming with Scala
Neelkanth Sachdeva
 
PPT
Cupdf.com introduction to-data-structures-and-algorithm
TarikuDabala1
 
Pattern Matching - at a glance
Knoldus Inc.
 
A Survey of Concurrency Constructs
Ted Leung
 
Getting Started With Scala
Xebia IT Architects
 
Java 103 intro to java data structures
agorolabs
 
camel-scala.pdf
Hiroshi Ono
 
1 list datastructures
Nguync91368
 
Introduction To R Language
Gaurang Dobariya
 
Functional Programming in Scala: Notes
Roberto Casadei
 
Core java concepts
laratechnologies
 
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
scalaliftoff2009.pdf
Hiroshi Ono
 
Introduction to matlab
Khulna University
 
Matlab1
guest8ba004
 
Arrays in Data Structure and Algorithm
KristinaBorooah
 
stacks and queues for public
iqbalphy1
 
C++ Standard Template Library
Ilio Catallo
 
Scala
Zhiwen Guo
 
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Functional programming with Scala
Neelkanth Sachdeva
 
Cupdf.com introduction to-data-structures-and-algorithm
TarikuDabala1
 

Similar to Fuel Up JavaScript with Functional Programming (20)

PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PDF
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
PPTX
Functional Programming Concepts for Imperative Programmers
Chris
 
PDF
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
PDF
Functional Programming in JavaScript
Will Livengood
 
ODP
Functional programming
S M Asaduzzaman
 
PDF
Functional Go
Geison Goes
 
PPT
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
PPT
Functional Programming Past Present Future
IndicThreads
 
PPTX
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
PDF
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
PPTX
Introduction to Functional Programming
Dave Fancher
 
PDF
Functional Programming for OO Programmers (part 1)
Calvin Cheng
 
PPTX
Unraveling the mystery of monads
Faisal Waris
 
PPTX
Thinking Functionally with JavaScript
Luis Atencio
 
PDF
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
PPTX
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
PDF
Functional programming
Hideshi Ogoshi
 
PDF
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
PDF
Functional programming 101
Maneesh Chaturvedi
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Functional Programming Concepts for Imperative Programmers
Chris
 
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional Programming in JavaScript
Will Livengood
 
Functional programming
S M Asaduzzaman
 
Functional Go
Geison Goes
 
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
IndicThreads
 
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Introduction to Functional Programming
Dave Fancher
 
Functional Programming for OO Programmers (part 1)
Calvin Cheng
 
Unraveling the mystery of monads
Faisal Waris
 
Thinking Functionally with JavaScript
Luis Atencio
 
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Functional programming
Hideshi Ogoshi
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
Functional programming 101
Maneesh Chaturvedi
 
Ad

Recently uploaded (20)

PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Ad

Fuel Up JavaScript with Functional Programming

  • 2. About Me  A passionate programmer finding my way around Functional Programming…  Work at UST Global  I occasionally blog at http://stoi.wordpress.com  Author of YieldJS & SlangJS  I recently co-authored a book with my colleague, friend and mentor called “.NET Design Patterns” by PACKT Publishing
  • 4. Leap ( A projectile at 90 degrees) Computing Paradigm  <Functional>  Imperative Paradigms with OOP  Domain Driven Design  Design Patterns  Object Functional  Reactive Programming  <Functional> Reactive Computing Platform  Single Core  Multi-core  Many-core  Clusters/Load-Balancers  Hypervisors  Virtual Machines  Cloud 100 Years
  • 5. JS Evolution (A snap-shot) Client Side  DHTML/Dom Manipulation  XMLHTTP/AJAX  jQuery (John Resig)  Web Frameworks  YUI, JQuery UI, Backbone, Knockout, Angular, Bootstrap etc.  Libraries  RxJs, Underscore, Prototype, Immutable, Redux, Lodash, Ramda etc.  Trans-compilers  Coffescript, Typescript, Flow etc.  Mobile Application Platforms  Hybrid – Sencha/Cordova based Server Side  Node.js (Ryan Dahl)  Node Modules  JS Libraries
  • 6. Being Functional Algorithm composition to be dealt on the same lines as mathematical function evaluations  Referential Transparency  Predictable  Transparent  Declarative  Composable  Modular
  • 7. Lambda (λ) calculus Alonzo Church Definition Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution var AddOperation = (x, y) => x + y; Lambda Abstraction : λx.x+y [f(x,y) = x + y] Variables : x & y Lambda Term : x + y Simplifications 1. Anonymous functions 2. Uses functions of a single input
  • 8. Lambda (λ) calculus - Continued  The following three rules give an inductive definition that can be applied to build all syntactically valid lambda terms:  A variable x, is itself a valid lambda term  If t is a lambda term, and x is a variable, then (λx.t) is a lambda term (called a lambda abstraction);  if t and s are lambda terms, then (ts) is a lambda term (called an application)
  • 9. Lambda (λ) calculus - Consequences λ Referential Transparency Anonymous Functions First-Class Functions Higher-Order Functions Closures Currying & Partial Application Recursion Memoization
  • 10. Referential Transparency Code Motivation Now since state of i is not guaranteed mutation-free AddOneRO (x) <> AddOneRO (y) if x = y, this further implies AddOneRO (x) - AddOneRO (x) <> 0 thus invalidating the fundamental mathematical identity x – x = 0
  • 11. Closures Code Motivation Now since state of i is not guaranteed mutation-free AddOneRO (x) <> AddOneRO (y) if x = y, this further implies AddOneRO (x) - AddOneRO (x) <> 0 thus invalidating the fundamental mathematical identity x – x = 0
  • 12. Currying Concept  Transforms a function that takes multiple arguments into a chain of functions each with a singleargument. a f (a,b,c) a b c
  • 13. Currying Implementation – ES5 Augmenting Types Closures Apply Invocation
  • 14. Currying Implementation – ES6 Closures Apply Invocation
  • 15. Partial Application – ES6 Transforms a function that take multiple arguments into afunction that accepts a fixed number of arguments, which in turn yields yet another function that accepts the remaining arguments.
  • 16. Recursion  Recursions are leveraged in functional programming to accomplish iteration/looping.  Recursive functions invoke themselves, performing an operation repeatedly till the base case is reached  Recursion typically involves adding stack frames to the call stack, thus growing the stack  You can run out of stack space during deep recursions
  • 17. Tail-Call Optimization  In this case, no state, except for the calling function's address, needs to be saved either on the stack or on the heap  Call stack frame for fIterator is reused for storage of the intermediate results.  Another thing to note is the addition of an accumulator argument (product in this case)
  • 18. Monads  Monad is a design pattern used to describe computations as a series of steps.  Monads wrap types giving them additional behavior like the automatic propagation of empty value (Maybe monad) or simplifying asynchronous code (Continuation monad).  Identity Monad  Wraps Itself  Maybe Monad  It can represent the absence of any value  List Monad  Represents a lazily computed list of values  Continuation monad  Binds the context
  • 19. JS Language Features That Aid Functional Programming ES5  First-class functions  Function objects  Lexical scoping  Function scope  Closures  Prototypal Inheritance  Augmenting Types  Function Invocation  Controlling context (with Apply & Call)  Array Methods  map, reduce, filter ES6  Arrow Functions  function*  yield, yield* expressions  Map object
  • 20. Scenario1  How do you add Exception Handling to your code-base without extensive code-change?
  • 21. Scenario2  You tend to write algorithms that operate more often on a sequence of items than on a single item.  More likely, you’ll perform several transformations between the source collection and the ultimate result.
  • 22. Scenario2 – Solution A  Iterating the collection once for every transformation (n iterations for n transformations)  Increases the execution time for algorithms with many transformations  Increases the application’s memory footprint as it creates interim collections for very transformation END Output List -> Interim List2 Transformation2 (Square) Interim List2 -> [1, 9, 25] Transformation1 (Filter Odds) Interim List1 -> [1, 3, 5] START Input List -> [1, 2, 3, 4, 5]
  • 23. Scenario2 – Solution B  Create one method that processes every transformation (1 iteration for n transformations)  Final Collection is produced in one iteration. This improves performance  Lowers the application’s memory footprint as it doesn’t create interim collections for every transformation  Sacrifices Reusability (of individual transformations) END Output List -> Interim List1 Transformation1 (Filter Odds + Square) Interim List1 -> [1, 9, 25] START Input List -> [1, 2, 3, 4, 5]
  • 24. Scenario2 – Solution C  Iterators  Enables you to create methods that operate on a sequence  Iterator methods do not need to allocate storage for the entire sequence of elements  Process and return each element as it is requested (Deferred Execution)
  • 25. Step in  A JavaScript library for creating Iterators, Generators and Continuation methods for Arrays.  The Iterator would be a method getIterator() that augments the Array data type and would have the following interfaces:  moveNext (method)  current (property)  reset (method) ITERATOR • Input List [1,2,3,4,5] MoveNEXT • 1 <- Square(FilterODD(1))-> OutputList [1] MoveNEXT • 2 <- FilterODD(2)-> MoveNEXT • 3 <- Square(FilterODD(3))-> OutputList [1,9] MoveNEXT • 4 <- FilterODD(4)-> MoveNEXT • 5 <- Square(FilterODD(5))-> OutputList [1,9,25]
  • 26. ES6 – Generators & Iterators  function*  The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.  Generator Object  The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.  Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
  • 27. Concluding  The proof is in the pudding!!!

Editor's Notes

  • #7: Output of these functions would purely depend on the inputs provided Moreover, any applicable data structures that the algorithm would need to create the output would be transient, having a lifetime within the function scope, and thus help in avoiding state mutation