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. Functional Programming in
    JavaScript
    Anil Wadghule
    λ

    View Slide

  2. • ?
    • ?
    • ?
    • ?
    • ?
    • ?
    • ?
    • ?
    What is Functional Programming?

    View Slide

  3. What is Functional Programming?
    • First class Functions
    • Higher Order Functions
    • Declarative Style
    • Closures
    • Recursion
    • Immutability
    • Pattern Matching
    • Lazy Evaluation

    View Slide

  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

    View Slide

  5. Is JavaScript Object Oriented or Functional?

    ❤️ child of Self and Scheme

    View Slide

  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`

    View Slide

  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 λ

    View Slide

  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.

    View Slide

  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

    View Slide

  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()

    View Slide

  11. Object Oriented Interaction
    ShowButton
    click()
    HiddenPanel
    show()
    InfoPanel
    show()
    display()

    View Slide

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

    View Slide

  13. View Slide

  14. Functional Style
    md toHTML modifyDOM
    postProcess
    Problem broken into Functional Parts

    View Slide

  15. Functional Style
    md toHTML postProcess modifyDOM
    Functions are also composed together to form more behaviours.
    visit
    post
    addId
    genID
    composed of

    View Slide

  16. Functional Style
    md toHTML postProcess modifyDOM
    text html decorated html

    View Slide

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

    View Slide

  18. Functions as Units of Abstraction
    Make it run, make it right, make it fast
    functions hide implementation details from view.

    View Slide

  19. You have already done FP in JS

    [1, 2, 3].forEach(alert); 


    View Slide

  20. You have already done FP in JS

    $.ajax({
    url: "test.html",
    context: document.body
    }).done(function() {
    $(this).addClass("done");
    });

    View Slide

  21. More examples of FP in JS
    That you already know
    ?

    View Slide

  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

    View Slide

  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

    View Slide

  24. Scope
    • Scope
    • Global Scope
    • Lexical Scope
    • Dynamic Scope
    • Function Scope

    View Slide

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

    //=> ["ella pugallum iraivanukke", "ella pugallum

    iraivanukke”]

    View Slide

  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"]

    View Slide

  27. Dynamic Scope
    function globalThis() { return this; }
    globalThis();
    //=> some global object, probably Window 

    globalThis.call(‘mustafa');
    //=> ‘mustafa’

    globalThis.apply(‘zariya', [])
    //=> ‘zariya’

    View Slide

  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

    View Slide

  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.

    View Slide

  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

    View Slide

  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 


    View Slide

  32. Applicative Functions
    • Map
    • Reduce
    • Filter

    View Slide

  33. Applicative Functions
    Lets see code

    View Slide

  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]

    View Slide

  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]

    View Slide

  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));

    View Slide

  37. Composition

    // Simple Compose function
    var compose = function (f, g) {
    return function(x) {
    return f.call(this, g.apply(this, arguments));
    }
    };

    View Slide

  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));

    View Slide

  39. Composition Problem
    Part of Speech Detector

    View Slide

  40. Benefits of FP
    • Simplicity
    • Expressive code (Declarative code)
    • Unit testing
    • Easy debugging
    • Concurrency (In JavaScript? - NO)
    • Hot Code Deployment (In JavaScript? - NO)

    View Slide

  41. Code examples can be found at
    https://gist.github.com/anildigital/082cca114c4e72b9b31e

    View Slide

  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

    View Slide

  43. Thank you
    @anildigital
    λ

    View Slide