Javascript Slides

JavaScript as a Functional Language

Source: 1/21

Zachary Kessin


Programming HTML5 Applications


Source: 2/21

History of Javascript

JavaScript has moved from a toy player to a major application language


  • 1994 Created by Brendan Eich at Netscape
  • 1994/1995 Renamed to "LiveScript" Then "JavaScript"
  • 1995 released in Netscape 2.0
  • 1996 Added to Internet Explorer
  • 1997 Support for Dom/ HTML4
  • 2005 Ajax
  • 2006 jQuery
  • 2009 Node.js
  • 2009 HTML5
Source: 3/21

Growth of JavaScript

Major browser vendors in compititon to build a fast engine

  • Google Chrome
  • Firefox
  • Microsoft Internet Exporer
  • Opera
  • Apple Safari

Speed ups of a few hundred x over IE 6.

Major Server implentations

  • Node.js
  • CouchDB
  • MongoDB
Source: 4/21

JavaScript as a Compile Target

JavaScript has of late become the language to use as a compile target

  • CoffeeScript
  • ClojureScript
  • GWT (Java -> JavaScript)
  • Haskell to JavaScript
Source: 5/21

Functions: The best thing in JavaScript

JavaScript Got some things very wrong but did get something quite right: Functions

  • JavaScript functions are first class citizens
  • JavaScript functions are also objects with properties and a prototype
  • JavaScript functions are subject to closure
Source: 6/21

Syntactic Sugar

JavaScript is a language with a lot of Syntactic Sugar

  • As in Lisp it is easy to build up the language for the task at hand
  • Example jQuery: Probably the most widely used Functional Programing library in the world
Source: 7/21

Declaring functions

JavaScript has two methods to create a function

  • Function Literal

    function square(x){
      return x * x;
  • Function Statement

    var square = function square(x){
      return x * x ;
  • Literals can only be used in some places
  • Literals are subject to hoisting
  • Statements can be used in any place where an expression is valid
  • Giving a name in a statement is useful for debugging and recursion
Source: 8/21


A JavaScript function created inside a larger function has access to the lexical variables of that function.

  • Closures are borrowed from Scheme
  • Closures allow a function to carry with it context from a prior function
Source: 9/21

Methods of Invocation

  • JavaScript has four ways to invoke a function
  • as a function
           var sum = add( 10, 20);
  • As a method
           var name = record.get('name');
  • As a consturctor
           var myUser = new User({...});
  • By call or apply
          var numbers = [3,4,5,6,7,8];
          var sum = add.apply({}, numbers) 
Source: 10/21

Scope: The hidden gotcha in a function

this is not subject to closure, so unless it is explicitly set it will default to the global window object

  • Every JavaScript function has an implicit variable this
  • this may be your problem.
  • this may really be that
  • this will default to the global window object
  • this will be the created object in a constructor
  • this will be the object in a method
Source: 11/21

Setting this with apply

  • function.apply() allows you to explicitly set the this object
  • A functional pattern, to create a wrapper to bind the inner function
  • Bound this
    Function.prototype.bind = function (target){
        var that = this;
        return function bind()
           return that.apply(target, arguments);  
    }; };
Source: 12/21

List Operations

Recent versions of JavaScript feature a full set of operations on Arrays.

  • map transforms one list into a new one
  • filter Selects a subset of a list
  • every returns true if all elements satisfy a predicate
  • some returns true if at least 1 element satisfies a predicate
  • reduce Ideal for building up composite data
  • reduceRight same as [...].reverse().reduce()

Guidelines for use

  • Use simple functions
  • Composition works well
  • Test the functions well
Source: 13/21

Map/Filter Example

var list = [2,4,16, 25, 18];
var squareroots = list.filter(isPerfectSquare).map(function (n){
    return Math.sqrt(n);

Will return this list


A more robust example, extract data from a record

Array.prototype.pick = function (field)
   return this.filter(function (v){
        return v[field]!== undefined;
    }).map(function return (v){
        return v[field];
Source: 14/21

Pattern: Chained Operations


need to perform several loosely connected operations on data


Chain Simple functional operations

jQuery uses the chain patterns a lot, by having each method return this it is possible to compose complex behaviors from simple functions.

  • Functions that return a value can be chained
  • When in doubt have a function return this
$('#show').text("Click to Hide").addClass('alert').fadein(4 * 1000).click(function()
  $(this).fadeout(4 * 1000).removeClass('alert');
  return this; 
Source: 15/21

Pattern: Function Compostion


Given two functions f and g create a function fg


var compose = function (f, g){
   return function (x){
      return f(g(x));
Source: 16/21

Pattern: Higher Order Functions


Sometimes class of problems will present in which most of the behaviors is repeated but with a small variation


A Higher order function, encode the part that changes as a passed function

Source: 17/21

Pattern: Recursing over an array


Need to handle a list of data in time consuming operations (EG Ajax), or where the list could grow.


Take the first element off of the list, process, recursively process the rest of the list

var process = function process(list, fn)
   if(list.length === 0)

if(list.length === 1) { fn(list[0], function (){}); return; }

fn(list[0], function callback(){ process(list.slice(1), fn);
}); }

Source: 18/21

Pattern: Monads

Monads are about the most powerful and most misunderstood functional pattern.

The Three laws of Monads

  • Monads wrap themselves around other data types
  • Monads have an operator that wraps the data
  • Monads have bind operation that allows the value in a monad to be extracted

When there is a class of functions that take one type and return a different type there are two functions that can be applied to make those functions be subject to composition

  • bind Take any function so that it takes the same type as it returns
  • unit That wraps a simple value into a monad
Source: 19/21

Pattern: Monads 2

jQuery is a monad

$() serves as a wrapping operation wrapping jQuery around DOM elements (unit)

$(...).html() return the content of the monad

Source: 20/21

Programming HTML5 Applications


Discount code: AUTHD

Source: 21/21


Table of Contents t
Source Files s
Slide Numbers n
Notes 2
Help h