Save 37% off PRO during our Black Friday Sale! »

Functional Programming in JavaScript

2ad20e87f55ce79b113a12c516ec9d09?s=47 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

2ad20e87f55ce79b113a12c516ec9d09?s=128

anildigital

February 03, 2015
Tweet

Transcript

  1. Functional Programming in JavaScript Anil Wadghule λ

  2. • ? • ? • ? • ? • ?

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

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

    Functional? • First class functions • Higher Order Functions • Closure • Applicative Functions • Imperative vs Declarative Style • Function Composition
  5. Is JavaScript Object Oriented or Functional? 
 ❤️ child of

    Self and Scheme
  6. 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`
  7. 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 λ
  8. 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.
  9. 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
  10. 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()
  11. Object Oriented Interaction ShowButton click() HiddenPanel show() InfoPanel show() display()

  12. Object Oriented Style Too many objects, too many states, mutations

    and hence s
  13. None
  14. Functional Style md toHTML modifyDOM postProcess Problem broken into Functional

    Parts
  15. Functional Style md toHTML postProcess modifyDOM Functions are also composed

    together to form more behaviours. visit post addId genID composed of
  16. Functional Style md toHTML postProcess modifyDOM text html decorated html

  17. Functional Style A functional program is a machine for transforming

    data
  18. Functions as Units of Abstraction Make it run, make it

    right, make it fast functions hide implementation details from view.
  19. You have already done FP in JS 
 [1, 2,

    3].forEach(alert); 

  20. You have already done FP in JS 
 $.ajax({ url:

    "test.html", context: document.body }).done(function() { $(this).addClass("done"); });
  21. More examples of FP in JS That you already know

    ?
  22. 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
  23. 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
  24. Scope • Scope • Global Scope • Lexical Scope •

    Dynamic Scope • Function Scope
  25. Global Scope aGlobalVariable = 'ella pugallum iraivanukke'; _.map(_.range(2), function() {

    return aGlobalVariable }); 
 //=> ["ella pugallum iraivanukke", "ella pugallum
 iraivanukke”]
  26. 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"]
  27. Dynamic Scope function globalThis() { return this; } globalThis(); //=>

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

    0; i < n; i++); return i; } // strangeLoop(5) //=> 5 // i // ReferenceError: i is not defined
  29. 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.
  30. 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
  31. 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 

  32. Applicative Functions • Map • Reduce • Filter

  33. Applicative Functions Lets see code

  34. 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]
  35. 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]
  36. 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));
  37. Composition 
 // Simple Compose function var compose = function

    (f, g) { return function(x) { return f.call(this, g.apply(this, arguments)); } };
  38. 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));
  39. Composition Problem Part of Speech Detector

  40. Benefits of FP • Simplicity • Expressive code (Declarative code)

    • Unit testing • Easy debugging • Concurrency (In JavaScript? - NO) • Hot Code Deployment (In JavaScript? - NO)
  41. Code examples can be found at https://gist.github.com/anildigital/082cca114c4e72b9b31e

  42. 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
  43. Thank you @anildigital λ