2

I'm very new to programming and have a quick question regarding a demonstration of closure given here: http://youtu.be/hQVTIJBZook?t=27m19s.

The code is:

var digit_name = function () {
    var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    return function (n) {
        return names[n];
    };
} ();

alert(digit_name(3));

My question is: Why is there an additional (); outside of the function digit_name? Are we calling the anonymous secondary function? I ran it without the (); and it came back with " function (n) {return names[n];} ". I would really appreciate a description of what happens to the parameter 3 when you pass it to the function digit_name, since that function doesn't have a specified parameter.

I apologize if I'm asking a basic question or using incorrect terminology. I've looked into a few related questions but alas, to no avail! Thank you in advance to those kind enough to provide a well-fashioned answer.

zastrowm
  • 8,017
  • 3
  • 43
  • 63
userNaN
  • 506
  • 1
  • 5
  • 13
  • Those are not supposed to be there.... – Kylie Jun 09 '13 at 04:24
  • 2
    "()" are there to actually call the function to get `digit_name = ` – mishik Jun 09 '13 at 04:25
  • Of course, don't forget to the read the StackOverflow explanation of [Javascript Closures](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1) – zastrowm Jun 09 '13 at 04:40
  • possible duplicate of [What do empty parentheses () after a function declaration do in javascript?](http://stackoverflow.com/questions/2422026/what-do-empty-parentheses-after-a-function-declaration-do-in-javascript) – Felix Kling Jun 09 '13 at 07:13

1 Answers1

2

In that code, it makes the outer function execute immediately, thus returning the inner function as digit_name. But since the returned function carries a reference to names, the scope of the outer function does not terminate like it normally should. Thus, the scope lives and it becomes a closure.

It's like doing:

function anon() {
  var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  return function (n) {
    return names[n];
  };
}

var digit_name = anon();

alert(digit_name(3));

So when you call digit_name(), you are actually calling the returned inner function which carries it's own names.

I suggest you read about closures at MDN. I also have an article discussing about closures in simple terms.

Joseph
  • 117,725
  • 30
  • 181
  • 234