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

PDF
Programming in Scala - Lecture Four
PDF
Programming in Scala - Lecture Three
PDF
Programming in Scala - Lecture Two
PDF
Programming in Scala - Lecture One
PDF
Python Programming - VII. Customizing Classes and Operator Overloading
PPTX
Data structure and algorithm using java
PPTX
Advanced Functional Programming in Scala
PPTX
Monadic genetic kernels in Scala
Programming in Scala - Lecture Four
Programming in Scala - Lecture Three
Programming in Scala - Lecture Two
Programming in Scala - Lecture One
Python Programming - VII. Customizing Classes and Operator Overloading
Data structure and algorithm using java
Advanced Functional Programming in Scala
Monadic genetic kernels in Scala

What's hot (20)

ODP
Pattern Matching - at a glance
PDF
A Survey of Concurrency Constructs
PDF
Getting Started With Scala
PPTX
Java 103 intro to java data structures
PDF
camel-scala.pdf
PPT
1 list datastructures
PPTX
Introduction To R Language
PDF
Functional Programming in Scala: Notes
PPTX
Core java concepts
PDF
Introduction à Scala - Michel Schinz - January 2010
PDF
scalaliftoff2009.pdf
PPTX
Introduction to matlab
PPT
Matlab1
PPTX
Arrays in Data Structure and Algorithm
PPTX
stacks and queues for public
PDF
C++ Standard Template Library
PPT
Scala
ODP
Functors, Applicatives and Monads In Scala
ODP
Functional programming with Scala
PPT
Cupdf.com introduction to-data-structures-and-algorithm
Pattern Matching - at a glance
A Survey of Concurrency Constructs
Getting Started With Scala
Java 103 intro to java data structures
camel-scala.pdf
1 list datastructures
Introduction To R Language
Functional Programming in Scala: Notes
Core java concepts
Introduction à Scala - Michel Schinz - January 2010
scalaliftoff2009.pdf
Introduction to matlab
Matlab1
Arrays in Data Structure and Algorithm
stacks and queues for public
C++ Standard Template Library
Scala
Functors, Applicatives and Monads In Scala
Functional programming with Scala
Cupdf.com introduction to-data-structures-and-algorithm
Ad

Similar to Fuel Up JavaScript with Functional Programming (20)

PDF
Scala for Machine Learning
PPTX
Concurrency Constructs Overview
PDF
Евгений Бурмако «scala.reflect»
PDF
scala.reflect, Eugene Burmako
PDF
Short intro to scala and the play framework
PPT
Scala Talk at FOSDEM 2009
PDF
Clojure intro
PPTX
Java8: what's new and what's hot
ODP
Functional Programming With Scala
PDF
Charles Sharp: Java 8 Streams
PPTX
Java 8 lambda
PPT
Design patterns represent the best practices used by experienced object-orien...
PPT
10-DesignPatterns.ppt
PDF
Automatic Task-based Code Generation for High Performance DSEL
PDF
Oct.22nd.Presentation.Final
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
PDF
PythonStudyMaterialSTudyMaterial.pdf
PDF
Introduction to new features in java 8
ODP
Patterns in Python
 
Scala for Machine Learning
Concurrency Constructs Overview
Евгений Бурмако «scala.reflect»
scala.reflect, Eugene Burmako
Short intro to scala and the play framework
Scala Talk at FOSDEM 2009
Clojure intro
Java8: what's new and what's hot
Functional Programming With Scala
Charles Sharp: Java 8 Streams
Java 8 lambda
Design patterns represent the best practices used by experienced object-orien...
10-DesignPatterns.ppt
Automatic Task-based Code Generation for High Performance DSEL
Oct.22nd.Presentation.Final
ScalaDays 2013 Keynote Speech by Martin Odersky
PythonStudyMaterialSTudyMaterial.pdf
Introduction to new features in java 8
Patterns in Python
 
Ad

Recently uploaded (20)

PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
L1 - Introduction to python Backend.pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
ai tools demonstartion for schools and inter college
PPTX
Presentation of Computer CLASS 2 .pptx
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PPT
Introduction Database Management System for Course Database
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
System and Network Administration Chapter 2
PDF
Digital Strategies for Manufacturing Companies
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Online Work Permit System for Fast Permit Processing
How Creative Agencies Leverage Project Management Software.pdf
Understanding Forklifts - TECH EHS Solution
Upgrade and Innovation Strategies for SAP ERP Customers
L1 - Introduction to python Backend.pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
2025 Textile ERP Trends: SAP, Odoo & Oracle
ai tools demonstartion for schools and inter college
Presentation of Computer CLASS 2 .pptx
A REACT POMODORO TIMER WEB APPLICATION.pdf
Introduction Database Management System for Course Database
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
System and Network Administration Chapter 2
Digital Strategies for Manufacturing Companies
PTS Company Brochure 2025 (1).pdf.......
ISO 45001 Occupational Health and Safety Management System
Materi_Pemrograman_Komputer-Looping.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Online Work Permit System for Fast Permit Processing

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