How does this JavaScript closure-function reuse an object without a global variable?

Viewed 1556

I decided to make one step forward on trying to understand Javascript and read again Javascript: The Good Parts. And here comes the first doubt:

Let's say I want to avoid using the global variables because they are evil, and so I have the following:

var digit_name = function(n) {
 var names = ['zero','one','two','three'];
 return names[n];
}

D.Crockford claims that this is slow because everytime the function gets called, a new instantiation of names is done. So, then he moves to the closure solution by doing this:

var digit_name = function () {
  var names = ['zero', 'one', 'two', 'three'];
  return function (n) {
    return names[n];
  }
}();

This makes the names variable stored in memory and therefore it doesn't get instantiated every time we call digit_name.

I want to know why? When we call digit_name, why is the first line being "ignored"? What am I missing? What is really happening here?

I have based this example not just in the book, but on this video (minute 26)

(if someone thinks of a better title, please suggest as appropriate...)

3 Answers
Related