Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming in JavaScript

anildigital
February 03, 2015

Functional Programming in JavaScript

This talk was presented at Expertalks happened on 31st Jan 2015 at Equal Experts India office.

Code snippets can be found here https://gist.github.com/anildigital/082cca114c4e72b9b31e

anildigital

February 03, 2015
Tweet

More Decks by anildigital

Other Decks in Technology

Transcript

  1. • ? • ? • ? • ? • ?

    • ? • ? • ? What is Functional Programming?
  2. What is Functional Programming? • First class Functions • Higher

    Order Functions • Declarative Style • Closures • Recursion • Immutability • Pattern Matching • Lazy Evaluation
  3. Overview • What is Functional Programming? • Why is JavaScript

    Functional? • First class functions • Higher Order Functions • Closure • Applicative Functions • Imperative vs Declarative Style • Function Composition
  4. Self • From Self, a powerful, if somewhat unusual, OO

    system • Dynamic dispatch • Encapsulation • Polymorphism — lots of it (weak typing!) • Inheritance through the prototype chain • Open recursion — through `this`
  5. Scheme • From Scheme, the most important features of functional

    languages • First class functions • Closures We are going to ignore OO & focus on first class functions λ
  6. Bare-bones introduction to FP Functional programming is the use of

    functions that transform values into units of abstraction, subsequently used to build software systems.
  7. Object Oriented Style Client Component operation() add(Component) remove(Component) getChild(int) Leaf

    Composite operation() add(Component) remove(Component) getChild(int) Children operation() Problem broken into Object Oriented Parts
  8. Object Oriented Style Client Component operation() add(Component) remove(Component) getChild(int) operation()

    add(Component) remove(Component) getChild(int) Children Component show() Component show() Composite Button show()
  9. Functional Style md toHTML postProcess modifyDOM Functions are also composed

    together to form more behaviours. visit post addId genID composed of
  10. Functions as Units of Abstraction Make it run, make it

    right, make it fast functions hide implementation details from view.
  11. You have already done FP in JS 
 $.ajax({ url:

    "test.html", context: document.body }).done(function() { $(this).addClass("done"); });
  12. First Class Functions • A function can be stored in

    variable • A function can be stored in an array • A function can be stored in object field • A function can be created as needed
  13. Higher Order Functions • A function can be stored in

    variable • A function can be stored in an array • A function can be stored in object field • A function can be created as needed • A function can be passed to other function • A function can be returned from a function
  14. Global Scope aGlobalVariable = 'ella pugallum iraivanukke'; _.map(_.range(2), function() {

    return aGlobalVariable }); 
 //=> ["ella pugallum iraivanukke", "ella pugallum
 iraivanukke”]
  15. Lexical Scope aVariable = "Outer"; function afun() { var aVariable

    = "Middle"; return _.map([1, 2, 3], function(e) { var aVariable = "In"; return [aVariable, e].join(' '); }); } // What is the value of a call to afun ? afun(); //=> ["In 1", "In 2", "In 3"]
  16. Dynamic Scope function globalThis() { return this; } globalThis(); //=>

    some global object, probably Window 
 globalThis.call(‘mustafa'); //=> ‘mustafa’
 globalThis.apply(‘zariya', []) //=> ‘zariya’
  17. Function Scope function strangeLoop(n) { var i; for (i =

    0; i < n; i++); return i; } // strangeLoop(5) //=> 5 // i // ReferenceError: i is not defined
  18. Closure A closure is an inner function that has access

    to the outer (enclosing) function's variables — scope chain. 
 The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.
  19. Closure 
 function showName(firstName, lastName) { var nameIntro = "Your

    name is "; // this inner function has access to the outer 
 // function's variables, including the parameter function makeFullName() { return nameIntro + firstName + " " + lastName; } return makeFullName(); } showName("AR", "Rahman"); // Your name is AR Rahman
  20. Closure 
 function makeAdder(x) { return function(y) { return x

    + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 

  21. Imperative Style 
 // Imperative style var numbers = [1,2,3,4,5];

    var doubled = []; for(var i = 0; i < numbers.length; i++) { var newNumber = numbers[i] * 2; doubled.push(newNumber); } console.log(doubled); //=> [2,4,6,8,10]
  22. Declarative Style var numbers = [1,2,3,4,5]; var doubled = numbers.map(function(n)

    { return n * 2; }); console.log(doubled); //=> [2,4,6,8,10]
  23. Composition // Simple Compose function var compose = function (f,

    g) { return function(x) { return f(g(x)); } };
 
 var f = compose(negate, square); console.log(f(2));
  24. Composition 
 // Simple Compose function var compose = function

    (f, g) { return function(x) { return f.call(this, g.apply(this, arguments)); } };
  25. Composition 
 var compose = function() { var funcs =

    arguments; return function() { var args = arguments; for (var i = funcs.length; i --> 0;) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; var f = compose(negate, square, mult2, add1); console.log(f(2));
  26. Benefits of FP • Simplicity • Expressive code (Declarative code)

    • Unit testing • Easy debugging • Concurrency (In JavaScript? - NO) • Hot Code Deployment (In JavaScript? - NO)
  27. Reference • Functional JavaScript - Michael Fogus • http://javascriptissexy.com/understand-javascript- closures-with-ease/

    • http://latentflip.com/imperative-vs-declarative/ • http://scott.sauyet.com/Javascript/Talk/Compose/ 2013-05-22