Overview • What is Functional Programming? • Why is JavaScript Functional? • First class functions • Higher Order Functions • Closure • Applicative Functions • Imperative vs Declarative Style • Function Composition
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`
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 λ
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.
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
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
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"]
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.
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