Javascript Slides

JavaScript as a Functional Language

Source: talk.md 1/21

Zachary Kessin

zkessin@gmail.com

@zkessin

Programming HTML5 Applications

cover

Source: talk.md 2/21

History of Javascript

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

History

  • 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: talk.md 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: talk.md 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: talk.md 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: talk.md 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: talk.md 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: talk.md 8/21

Closures

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: talk.md 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: talk.md 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: talk.md 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: talk.md 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: talk.md 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

 
[2,4,5]

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: talk.md 14/21

Pattern: Chained Operations

Problem

need to perform several loosely connected operations on data

Solution

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: talk.md 15/21

Pattern: Function Compostion

Problem

Given two functions f and g create a function fg

Solution

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

Pattern: Higher Order Functions

Problem

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

Solution

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

Source: talk.md 17/21

Pattern: Recursing over an array

Problem

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

Solution

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)
   {
    return;
   }

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

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

Source: talk.md 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: talk.md 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: talk.md 20/21

Programming HTML5 Applications

cover

Discount code: AUTHD

Source: talk.md 21/21

Help

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