Thursday, March 31, 2011

Functions in Javascript

In Javascript functions are first-class objects.
In computing, a first-class object (also value, entity, and citizen), in the context of a particular programming language, is an entity that can be passed as a parameter, returned from a subroutine, or assigned into a variable.

This means that Javascript can support functional programming constructs such as anonymous functions, higher order functions, nested functions, closures, currying etc.

This is best understood through an example :
function sum(a,b) {return a+b}
function incrementer(a) {
  return function(b) { //here we are returning a function and also
    //creating an anonymous function
    return sum(a,b); //here we are using closure by
    //referring to local variable a of the incrementer function
  }
}
var incrementBy1 = incrementer(1);
incrementBy1(10); //returns 11
var incrementBy2 = incrementer(2);
incrementBy2(10); //returns 12