Archive

Posts Tagged ‘closures’

Closures vs Objects: FIGHT

September 23rd, 2011 11 comments

In JavaScript, there are two main patterns for creating objects with state - plain JavaScript objects and closures. In this post I’m going to highlight the similarites and consider the pros and cons of the two approaches.

An object is an entity with state and methods to access/modify that state. There are two main approaches to this, which I’ll be calling “objects” and “closures”. For the rest of this post I’ll only use the word object to refer to plain JavaScript objects, in an attempt to avoid confusion.

//object
function Person(name) {
  this.name = name;
}

Person.prototype.sayHi = function () {
  console.log('Hi there, my name is ' + this.name);
};


//closure
function person(name) {
  //using object literal but state held in closure, not in object
  return {
    sayHi: function () {
      console.log('Hi there, my name is ' + name);
    }
  };
}

Now, there are infinite variations to the above. I’m using native JavaScript constructors in the object version, but it doesn’t have to be that way. For example, I could make a function that returns an object, without having to use new:

//alternative object
function person(name) {
  return {
    name: name,
    sayHi: function () {
      console.log('Hi there, my name is ' + this.name);
    }
  };
}

Alternatively, I could come up with a more convoluted example that caches the sayHi method so it’s shared between instances.

The point is, using objects, state is shared through this. Whenever you call a method on an object, e.g.

var dave = new Person('Dave');
dave.sayHi();

this within the method will be equal to the object it was called upon. When using closures however, state is shared through the lexical scope. This highlights the first key difference between objects and closures: access to the internal state.

There are three ways to mutate the internal state of an object in JavaScript. I’ll illustrate with some examples:

//Obtain a reference to the object and assign new properties
function changeName(object, newName) {
  object.name = newName;
}

changeName(dave, 'Bob');


//Attach a function to the object and call it as a method on the object
function changeName(newName) {
  this.name = newName;
}

dave.changeName = changeName;
dave.changeName('Bob');


//call/apply a function with the object as the context
changeName.call(dave, 'Bob');

With closures, on the other hand, there is only one way to mutate the internal state – be inside the scope of the closure:

function person(name) {
  //to change `name`, you *must* be defined somewhere inside this function

  return {
    sayHi: function () {
      console.log('Hi there, my name is ' + name);
    }
  };
}

This can be a blessing and a curse. The advantage of objects over closures is that you’re not limited in the functionality you can add to an object by location in the source code. If you decide that you need to add more functionality to an object, you can do this at any point in your codebase. With a closure the only way to add functionality (with access to the internal state) is to define it somewhere inside the function that creates the closure.

The advantage of closures over objects is the same as the disadvantage but from the perspective of third party code. With an object, anybody can add or change functionality on your object, and access its internal state. With a closure, the internal state is private – it can’t be accessed from outside the closure without the use of accessor functions.

Another advantage that objects have is in terms of memory usage. With a closure, by definition, for a function to have access to the internal state it must be defined inside the closure. That means that each new closure created must have its own version of the function. Objects on the other hand have no such limitation. A function that reads from and writes to this need only be defined once – it can then be added to any object, either shared via the prototype system or through other means.

An advantage that closures have is that you don’t need to keep track of this. With closures it’s simple – you’re either in the correct scope or you’re not. With objects, if you’re in a method called on an object then this is that object, but if the method gets detached from its object (e.g. when passed as an argument) it loses its binding, or if you have a nested function inside the method. Then you need to start messing about with call and apply, and bind and other fun stuff.

So, when should you use objects and when closures? If you’re making hundreds of object-type things then they should probably be objects. If there are only a few and you have security concerns then closures are a better bet.

Privacy isn’t just a security issue – it’s useful for creating a clean separation between the public API and the private implementation. Some developers would say that JavaScript doesn’t provide privacy, so you should get used to writing objects with everything public, and tell users of your code to just not touch certain properties (for example those with a leading underscore). I think it’s useful being able to enforce privacy – it makes sure that no-one will ever write code that’s reliant on an implementation detail of yours.

Because of this, I tend to favour closures, falling back to objects when memory becomes a concern, but that’s largely a personal preference.

Making inheritable objects in JavaScript without objects

August 14th, 2011 1 comment

For a long time I’ve found the subject of the equivalence of closures and objects fascinating. The problem with creating objects using closures is that there isn’t a way to do inheritance (although you should always favour composition over inheritance anyway!). I thought it would be fun to see if it was possible to implement an object system in JavaScript with inheritance, without using any plain JavaScript objects.

To do this, I set myself two rules:

  1. Don’t create any plain old JavaScript objects (functions, arrays etc. are allowed)
  2. Don’t use the dot operator.

For that to work, I wrote some wrappers for the JavaScript methods I would need, like Array.prototype.slice.call (this becomes callSlice). Apart from those wrappers, there are no dots used anywhere. To dispatch methods based on a string name, instead of using an object (which would have been much easier but would have missed the point of the exercise) I’m passing around functions which dispatch methods using conditional constructs (if, else and switch).

Introducing funcobj!!!

Yeah I know, it’s a rubbish name. Anyway, the Github repo is here and I’ve got a running example on JsFiddle here.

Here’s some examples of how it works:

//call the doSomething method on myObject, with the argument 500
myObject('doSomething')(500);

//call the doSomethingElse method on the object's super object
myObject('doSomethingElse', true)();

To make an object like this, call objMaker with a function that defines and dispatches methods:

To inherit, pass a third argument to objMaker, which is the object to delegate to if the new object does not contain the called method (or: if the new object cannot respond to the message). Have a look at this long example in JsFiddle to see how that works:

This is stupid

Yeah, I know. It’s not meant to be used for anything. It’s probably hopelessly inefficient, and the syntax leaves a lot to be desired. But it does work, which was what I was going for. It might be a stupid idea, but it demonstrates the power of JavaScript closures. It also gives the possibility of dynamically responding to unknown messages, like in Ruby’s method_missing.

This is what objMaker looks like. There’s some fairly gnarly code in there, but if you can get your head around what’s doing what, you’ll hopefully learn something new about JavaScript!

Categories: Programming Tags: ,

Closures explained with JavaScript

April 22nd, 2011 18 comments

Last year I wrote A brief introduction to closures which was meant to help people understand exactly what a closure is and how it works. I’m going to attempt that again, but from a different angle. I think with these kinds of concept, you just need to read as many alternative explanations as you can in order to get a well rounded view.

First-class functions

As I explained in Why JavaScript is AWESOME, one of the most powerful parts of JavaScript is its first-class functions. So, what does “first-class” mean in a programming language? To quote wikipedia, something is first-class if it:

  • can be stored in variables and data structures
  • can be passed as a parameter to a subroutine
  • can be returned as the result of a subroutine
  • can be constructed at runtime
  • has intrinsic identity (independent of any given name)

So, functions in JavaScript are just like objects. In fact, in JavaScript functions are objects.

The ability to nest functions gives us closures. Which is what I’m going to talk about next…

Nested functions

Here’s a little toy example of nested functions:

The important thing to note here is that there is only one f defined. Each time f is called, a new function g is created, local to that execution of f. When that function g is returned, we can assign its value to a globally defined variable. So, we call f and assign the result to g5, then we call f again and assign the result to g1. g1 and g5 are two different functions. They happen to share the same code, but they were executed in different environments, with different free variables. (As an aside, we don’t need to use a function definition to define g and then return it. Instead, we can use a function expression which allows us to create a function without naming it. These are called ‘anonymous functions’ or lambdas. Here’s a version of the above with g converted to an anonymous function.)

Free variables and scope

A variable is free in any particular scope if it is defined within an enclosing scope. To make that more concrete, in the scope of g, the variable x is free, because it is defined within the scope of f. Any global variables are free within the scopes of f and g.

What do I mean by scope? A scope is an area of code where a variable may be defined, without the enclosing scope knowing about it. JavaScript has ‘function scope’, so each function has its own scope. So, any variable defined within f is invisible outside of f. Scopes can be nested, so in the above example, g has its own scope which is contained within the scope of f, which is contained within the global scope. Whenever a variable is accessed, the JavaScript interpreter first looks within the current scope. If the variable is not found to be defined within the current scope, the interpreter checks the enclosing scope, then the enclosing scope of the enclosing scope, all the way up to the global scope. If the variable is not found, a ReferenceError is thrown.

Closures are functions that retain a reference to their free variables

And this is the meat of the matter. Let’s look at a simplified version of the above example first:

It’s no surprise that when you call f with the argument 5, when g is called it has access to that argument. What’s a bit more surprising is that if you return g from the argument, the returned function still has access to the argument 5 (as shown in the original example). The bit that can be a bit mind-blowing (and I think generally the reason that people have such trouble understanding closures) is that the returned g actually is remembering the variable x that was defined when f was called. That might not make much sense, so here’s another example:

When person is called, the argument name is bound to the value passed. So, the first time person is called, name is bound to ‘Dave’, and the second time, it’s bound to ‘Mary’. person defines two internal functions, get and set. The first time these functions are defined, they have a free variable name which is bound to ‘Dave’. These two functions are returned in an array, which is unpacked on the outside to get two functions getDave and setDave. (If you want to return more than one value from a function, you can either return an object or an array. Using an array here is more verbose, but I didn’t want to confuse the issue by including objects as well. Here’s a version of the above using an object instead, if that makes more sense to you.)

And this is the magic bit. getDave and setDave both remember the same variable name, which was bound to ‘Dave’ originally. When setDave is called, that variable is set to ‘Bob’. Now when getDave is called, it returns ‘Bob’ (Dave never liked the name ‘Dave’ anyway). So getDave and setDave are two functions that remember the same variable. This is what I mean when I say “Closures are functions that retain a reference to their free variables”. getDave and setDave both remember the free variable name. Even though person has now returned, the variable name lives on, because it is referenced by getDave and setDave.

The variable name was bound to ‘Dave’ when person was called the first time. When person is called a second time, a new version of name comes into existence, as well as new versions of get and set. So the functions getMary and setMary are completely different to the functions getDave and setDave. They execute identical code, but in two different environments, with different free variables.

Summary

In summary, a closure is a function called in one context that remembers variables defined in another context – the context in which it was defined. Multiple closures defined within the same context remember that same context, so changes they make are shared between them. Every time a function is called that creates closures, a new, shared context is created for the new closures.

The best way to learn is to play, so I’d recommend editing the fiddles above (by clicking on the + at the top right) and having a fiddle. Enjoy!


Addendum: Lasse Reichstein had some useful comments on this post on the JSMentors mailing list – read them here. The important thing to realise is that a closure actually remembers its environment rather than its free variables, so if you define a new variable in the environment of the closure after the closure’s definition, it will be accessible inside the closure.

Zen and the art of statefulness

February 12th, 2011 15 comments

The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said “Master, I have heard that objects are a very good thing – is this true?” Qc Na looked pityingly at his student and replied, “Foolish pupil – objects are merely a poor man’s closures.”

Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire “Lambda: The Ultimate…” series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.

On his next walk with Qc Na, Anton attempted to impress his master by saying “Master, I have diligently studied the matter, and now understand that objects are truly a poor man’s closures.” Qc Na responded by hitting Anton with his stick, saying “When will you learn? Closures are a poor man’s object.” At that moment, Anton became enlightened.

Anton van Straaten

When I first read the above koan some time ago, I didn’t really understand it. I had a very basic idea of closures, but at the time they were just a syntactic oddity to me – something you could do a few cool things with, but not particularly useful. Since then I’ve worked through quite a bit of Structure and Interpretation of Computer Programs and delved into functional programming in JavaScript, which has given me a much deeper understanding of closures. On the other side of the divide, I’ve been doing a lot of Ruby programming, which has helped me grok objects a lot better. I now feel like I can begin to comprehend what the quote was getting at.

My moment of enlightenment came today while reading Test-Driven JavaScript Development and looking at the code for a JavaScript strftime function (abbreviated here for brevity):

Date.prototype.strftime = (function () {
  function strftime(format) {
    var date = this;

    return (format + "").replace(/%([a-zA-Z])/g, function (m, f) {
      //format date based on Date.formats
    });
  }

  // Internal helper
  function zeroPad(num) {
    return (+num < 10 ? "0" : "") + num;
  }

  Date.formats = {
    // Formatting methods
    d: function (date) {
      return zeroPad(date.getDate());
    },
    //...
    //various other format methods
    //...

    // Format shorthands
    F: "%Y-%m-%d",
    D: "%m/%d/%y"
  };

  return strftime;
}());

The above code uses an IIFE (Immediately-invoked function expression) to produce a function with additional data (if Date.formats was instead declared as a local variable, this would be a better example). If it doesn’t make sense, I thoroughly recommend Ben Alman’s post on IFFEs for an overview of the technique. The code executes, and returns a function. The important thing is that one function is used to define another function and its context.

In Ruby, when you define a class, the class definition is executed as Ruby code, unlike in Java, for example, where a class definition is just a syntactic construct read at compile-time, but not executed in the way other Java code is. A Ruby class definition is read at run-time, and builds up a new class as it is interpreted.

In a lot of ways, Ruby class definitions and JavaScript function-defining functions are equivalent. I’ll give you a little example to illustrate:

zen.js

var Cat = function () {
  var age = 1;

  function catYears() {
    return age * 7;
  }

  function birthday() {
    age++;
  }

  return {
    catYears: catYears,
    birthday: birthday
  }
};

var powpow = Cat();
var shorty = Cat();

//yo shorty, it's your birthday:
shorty.birthday();

alert(powpow.catYears()); // => 7
alert(shorty.catYears()); // => 14

zen.rb

class Cat
  def initialize
    @age = 1
  end

  def cat_years
    @age * 7
  end

  def birthday
    @age += 1
  end
end

powpow = Cat.new
shorty = Cat.new

#yo shorty, it's your birthday:
shorty.birthday

puts powpow.cat_years # => 7
puts shorty.cat_years # => 14

Strictly speaking, in zen.js I’m returning an object, but the private data and methods of that object are saved in a closure. So, zen.js stores its state in a closure, while zen.rb stores its state in an object. Every time Cat() is called in zen.js, a new closure is created with a unique age. Every time Cat.new is called in zen.rb, a new object is created with a unique @age. (These two examples aren’t strictly equivalent – each cat in zen.js gets a new copy of the functions, whereas in zen.rb they share the same methods. It’s possible to make the JavaScript version function more like a Ruby class definition, but it takes a bit more code.)

Of course, there’s a lot you can do with JavaScript closures that you can’t do with Ruby objects. And there’s a lot you can do with Ruby objects that can’t be emulated using JavaScript closures. Any time you decide that one is better than the other, just imagine Qc Na hitting you with his stick.

Further reading

Ruby vs JavaScript: functions, Procs, blocks and lambdas

January 15th, 2011 54 comments

In my post Why JavaScript is AWESOME I compared Ruby to JavaScript like this:

A language like Ruby is a toolbox with some really neat little tools that do their job really nicely. JavaScript is a leather sheath with a really really sharp knife inside.

What I was partly getting at was how the two languages handle the passing around of code. Both have their own way of working with anonymous functions. They’ve taken very different approaches, so if you’re moving from one language to the other it can be confusing. I’d like to try to explain the differences. Let’s look at JavaScript first.

JavaScript functions

JavaScript has two ways of defining functions – function expressions (FE) and function declarations (FD). It can be a confusing distinction because they look the same. The difference is that a function declaration always has the word function as the first thing on the line.

//Function declaration:
function doSomething() {
    alert("Look ma, I did something!");
}

//Function expression:
var somethingElse = function () {
    alert("This is a different function");
};

The FE can optionally contain a name after the function keyword so it can call itself. I’m not going to go into depth on FD vs FE, but if you’re interested in learning more read Ben Alman’s piece on Immediately-Invoked Function Expressions, which has a good description and some useful links.

You can think of an FE as a function literal, just like {a: 'cat', b: 'dog'} is an object literal. So they don’t just have to be assigned to variables – they can be passed as function arguments, returned from functions, and stored in data structures (objects and arrays). In the end though, there’s only one function type – doSomething and somethingElse are the same type of object.

Ruby

Ruby is at the opposite end of the scale to JavaScript. Instead of having just the one function type, it has multiple types: blocks, Procs, and lambdas. (There are also methods and method objects but that’s a different story.)

Blocks

A block in Ruby is a chunk of code. It can take arguments via its funky pipe syntax, and its return value is whatever the last line evaluates to. Blocks aren’t first-class citizens in Ruby like functions are in JavaScript – they can only exist in one place – as the last argument to a method call. They’re very much a special syntactic construct baked right into the language. All methods can received blocks whether they include a parameter for one or not – it will be received anyway, and you can interact with it without it having a name. It can be called with the yield keyword, and you can check to see if a block was supplied with block_given?. Robert Sosinski gives a good example of using blocks from the point of view of the caller and that of the receiver in his post Understanding Ruby Blocks, Procs and Lambdas:

class Array
  def iterate!
    self.each_with_index do |n, i|
      self[i] = yield(n)
    end
  end
end

array = [1, 2, 3, 4]

array.iterate! do |n|
  n ** 2
end

Procs

If you need a block of code to act as a first-class citizen, you need to turn it into a Proc. That can be achieved with Proc.new. This takes a block and returns a Proc. Pretty cool eh? Procs are useful where you’d want to use a block but you’re not passing it as the last argument to a method. Rails provides a good example:

class Order < ActiveRecord::Base
  before_save :normalize_card_number,
    :if => Proc.new { |order| order.paid_with_card? }
end

The :if => syntax shows that we’re passing a hash to before_save. We can’t put a block as a hash value, so we need to make a Proc instead. Other callbacks can just take a raw block:

class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create do 
    |user| user.name = user.login.capitalize if user.name.blank?
  end
end

For more discussion on Procs and blocks have a look at Eli Bendersky’s post: Understanding Ruby blocks, Procs and methods.

Lambdas

A lambda in Ruby is probably the closest thing to a function expression in JavaScript. A lambda is created similarly to Proc.new:

lambda { |x| x ** 3 }

Both lambda and Proc.new take a block and return an object. However, there are important differences in how they deal with their arguments and how they deal with return and break. To talk about that though I’ll need to go back to basics to discuss the reasons for using these self-contained chunks of code.

The reasons for using anonymous functions

There are a lot of good reasons to support anonymous functions in a programming language. In Ruby and JavaScript, the uses generally fall under two rough categories: iteration and deferred execution.

Iteration with anonymous functions

Iteration has a lot of uses – you can sort a collection, map one collection to another, reduce a collection down into a single value, etc. It basically comes down to going through a collection and doing something with each item, somehow. I’m going to show a very basic example of iteration – going through a list of numbers and printing each one.

In Ruby, there are two common ways to work through an array or other enumerable object, doing something to each item. The first is to use the for/in loop, which works like this:

arr = [1, 2, 3, 4]
for item in arr
  puts item
end

The second is to use the each iterator and a block:

arr = [1, 2, 3, 4]
arr.each do |item|
  puts item
end

Using iterators and blocks is much more common, so you’ll usually see it done like this.

JavaScript has a for/in loop as well, but it doesn’t really work very well on arrays. The standard way to iterate over an array is with the humble for loop:

var arr = [1, 2, 3, 4];
for (var i = 0, len = arr.length; i < len; i++) {
    console.log(arr[i]);
}

Many libraries offer support for something like Ruby’s each iterator – here is the jQuery version:

var arr = [1, 2, 3, 4];
$.each(arr, function(index, value) { 
    console.log(value); 
});

There’s an important difference here between the way Ruby and JavaScript handle the each iterator. Blocks in Ruby are specially designed for this kind of application. That means that they’ve been designed to work more like a looping language construct than an anonymous function. What does this mean practically? I’ll illustrate with an example:

arr = [1, 2, 3, 4]
for item in arr
  break if item > 2 #for non Rubyists, this is just like a compact if statement
  puts item
end

arr.each do |item|
  break if item > 2
  puts item
end

These two code snippets do the same thing – if item is greater than 2 iteration stops. On one level, this makes perfect sense – the each iterator takes a block of code, and if you want to stop iterating you break, as you would in any other language’s native foreach loop. On another level though, this doesn’t make any sense – break is used for loops, not anonymous functions. If you want to leave a function, you use return, not break.

Interestingly, if you use return inside a Ruby block, you don’t just return from the block, but the containing method. Here’s an example:

def find_first_positive_number(arr)
  arr.each do |x|
    if x >= 0
      return x
    end
  end
end

numbers = [-4, -2, 3, 7]
first = find_first_positive_number(numbers)

When arr.each gets to 3, find_first_positive_number will return 3. This demonstrates that in blocks in Ruby, the break and return keywords act as if the block was just a looping construct.

jQuery.each, on the other hand, is working with normal functions (there’s nothing else to work with in JavaScript). If you return inside the function passed to each, you’ll just return from that function, and each will move onto the next value. It’s therefore the equivalent of continue in a loop. To break out of the each entirely, you must return false.

So, in Ruby, break, continue and return work in the same way whether you’re using the for/in looping construct or using an iterator with a block. With a jQuery iterator, return is the equivalent of continue, return false is the equivalent of break, and there’s no equivalent of return without putting extra logic outside the loop. It’s easy to see why Ruby blocks were made to work this way.

Deferred execution

This is where a function is passed to another function for later use (this is often called a callback). For example, in jQuery.getJSON:

$.getJSON('ajax/test.json', function(data) {
    console.log(data);
});

The anonymous function isn’t executed until the JSON data comes back from the server. Similarly, with Rails:

class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create do |user|
    user.name = user.login.capitalize
  end
end

The block won’t be executed immediately – it’ll be saved away, ready to be executed as soon as a new User is created. In this case, break no longer makes sense – there’s no loop to break out of. return generally also doesn’t make sense in this case, as it may try to return to a function that has already returned. For more details on this see my question on Stack Overflow. This is where lambdas come to the rescue. A lambda in Ruby works much more like a Ruby method or a JavaScript function: return just leaves the lambda; it doesn’t try to exit the containing method.

So why use a block as a callback? Probably the best reason is that Ruby makes blocks so easy, so it’s simpler just to pass a block to the before_create method than to create a lambda and pass that (the before_create internals will be simpler as well).

Pros and cons

As I said at the beginning, Ruby and JavaScript have taken two extremely different approaches to functions. There’s a whole different discussion about methods across the two languages as well (JavaScript uses the same function type for methods, whereas Ruby has yet another type) but I’m not going to go there. Ruby has something different for every situation, and each one is optimised for its primary use-case. This can lead to confusion but can also make code easier to read. On the other hand, in JavaScript, a function is a function is a function. Once you know how they work, it’s easy.

There’s no point arguing about which of these two approaches is better – there’s no answer to that. Some people will prefer one over the other, but I like them both. I love the way blocks in Ruby make certain kinds of functional-like programming just roll off the fingers, but I also love the way JavaScript doesn’t complicate things, and makes proper functional programming much more possible.

If you made it this far, good on ya. I didn’t mean to write such a mammoth post, but sometimes these things happen. Cheers!

A brief introduction to closures

November 22nd, 2010 14 comments

In this post, I’m going to attempt to explain what closures are and how to use them. Many modern (and some not-so-modern) programming languages contain support for closures, but for the purposes of this article I’m going to be using JavaScript. I’ve chosen JavaScript for a few reasons:

  • Ubiquity: If you have a web browser then you have a JavaScript interpreter
  • Simplicity: JavaScript is conceptually a fairly simple language (especially if you limit yourself to its Good Parts), compared to other dynamic scripting languages such as Python and Ruby
  • Familiarity: If you’ve used any of the C family of languages (e.g. C++, Java or C#) then JavaScript will look fairly familiar.

There may be some differences between languages with the mechanics, but deep down, closures are the same across all languages which allow them, so if you can understand the concept in JavaScript, you’ll understand it in any capable language.

Functional programming

Before I can get onto closures, I need to give a very brief introduction to functional programming.

Functional programming is all about functions (I doubt that comes as much of a surprise). In a language that surports functional programming, functions are generally first-class objects. That means they can be assigned to variables, stored in data structures, passed into functions and returned from functions.

In JavaScript, it’s important to distinguish between referencing a function and calling a function. To reference a function, just use the function name. To call a function, append parentheses (with optional arguments). Here’s an example:

function f() {
    alert('f called!');
}

f(); // calls f
var x = f; // f is a reference to the function, and now x is too
x(); // calls f (or x - they're the same thing)

It’s also possible to create anonymous functions in JavaScript (aka lambdas). If you want to create an anonymous function, leave out the name:

function () {
    alert('I have no name');
}

Another name for an anonymous function is a function literal. If you imagine it like a string literal you’ll see it’s an expression just like any other literal, and so it can be assigned to a variable:

var str = "string"; //string literal
var arr = [1, 2, 3]; //array literal
var obj = { 'JS': 1,
            'is': 2,
            'awesome': 3 }; //object literal
var f = function () {
    alert("I've been assigned to f");
}; //function literal

Note that there is very little difference between assigning an anonymous function to a variable called f and defining a function called f – the end result of both is a function that can be referred to by the name f, and can be called with f().

Another capability of functional languages is the ability to nest functions. It’s perfectly valid in JavaScript to define one function within another. Here’s another example:

function outer() {
    function inner() {
        alert('In ur function');
    }
    inner(); // we can call inner here as it is defined in outer's scope
}
inner(); // Error - but not here - inner is not defined in this scope

It’s this ability, coupled with the first-class nature of functions, that enables closures.

A real-life closure

A closure is a function with access to variables in its containing scope (the function “closes over” the variables). The thing that can be tricky to wrap your head round is that the inner function still has access to the outer function’s variables after the outer function has returned. Here’s an example:

function outer() {
    var counter = 0;
    function inner() {
        alert(counter);
        counter++;
    }
    return inner;
}

var x = outer(); // As we're calling outer here, x is a reference to inner 
x(); // alerts 0
x(); // alerts 1
x(); // alerts 2

In this code, outer is called once, and returns inner. x is a reference to inner. Because inner is a closure, it has access to outer‘s local variable, counter. Even though outer has returned, inner still has access to outer‘s variables. Be careful though – if outer were called again, we’d get a new version of inner. To continue the previous example:

var y = outer(); // Call outer again
y(); // alerts 0 - this is a different closure to the previous one.

The closure has access to any arguments in the containing scope as well:

function outer(x) {
    function inner() {
        alert(x);
    }
    return inner;
}

var func = outer(5);
func(); //alerts 5 - inner has access to the argument

A more advanced example

You should now know enough about the basics of closures to understand a more complex example. Here’s a way to give a JavaScript object private variables:

function CatMaker(name) {
    var age = 10;

    //construct an object on the fly with three methods.
    //All methods have access to age, but age cannot be
    //directly accessed outside of this function.
    return { 
        "sayHello": function () { //first method
            alert("Miaow");
        },
        "getAge": function (inCatYears) { //second method
            if (inCatYears) {
                return age * 7;
            }
            else {
                return age;
            }
        },
        "makeOlder": function () { //third method
            age++;
        }
    };
}

var mycat = CatMaker('Snuffles');
mycat.getAge(true); //returns 70
mycat.makeOlder();
mycat.getAge(true); //returns 77

The ONLY way to make changes to the private variable age is through the method makeOlder. All the methods share the same age variable, because they were all made in the same call of CatMaker. If we called CatMaker again to produce a new cat, it would have its own age variable.

The infamous lambda-in-a-loop problem

Consider the following example:

function attachListeners() {
    for (var i = 0; i < 10; i++) {
        $('#id-' + i).click(function () {
            alert("I am element number " + i);
        });
    }
}

It’s using jQuery. To understand this example you’ll need to know a tiny amount of how jQuery works. jQuery creates a global function called jQuery, aliased to $. The jQuery function takes (among other things) a CSS selector. It returns a jQuery object representing the HTML elements matching that selector. A click handler can be added by calling .click() on the returned object. .click() takes a function to be executed when the matched elements are clicked on. $('#myid').click(function () { alert('hello'); }); will show an alert when the HTML element with an id of ‘myid’ is clicked on.

The example selects 10 elements on the page, with the ids id-0, id-2 up to id-9. Each time round the loop, a new click handler is created. When you click on these elements, an alert box comes up. Some would think that each click handler has its own version of i but you know better. All the click handlers share the same i. Because of the way the for loop works, this value is one past the end of the loop, i.e. 10. So each element proudly announces that it is element number 10, which is clearly incorrect.

The problem here is that although a new closure is being produced each time round the loop, each closure shares the same environment, so i in each closure is the same i as in all the others.

Take a look at a working demonstration of the above code using jsFiddle. Have a play with it so you can get a feel for what’s going on.

The only way around this is to use another function:

function addOneListener(i) { //Each time i is bound to a different value
    $('#id-' + i).click(function () {
        alert("I am element number " + i);
    });
}

function addEventListeners() {
    for (var i = 0; i < 10; i++) {
        addOneListener(i); 
    }
}

Here’s the above as a fiddle. emehrkay in the comments has an alternative implementation of the above using raw DOM methods – it’s often useful to see different ways of achieving the same thing.

The key to understanding the new example is that every time addOneListener is called, a new closure is produced, and each of these closures has a different i. When you start using closures in JavaScript, this will bite you eventually, so beware. It’s such a common issue that bobince of HTML-parsing regex fame put it at number three in his list of common questions on Stack Overflow:

At number three it’s a new entry for “Why is my (Python, JavaScript, …) function getting the same value of the variable every time around the loop?”, by Clint Forloop and the Closures