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.

4

1 Answer 1

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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.