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
  • Those are not supposed to be there.... Commented Jun 9, 2013 at 4:24
  • 2
    "()" are there to actually call the function to get digit_name = <result of calling the function> Commented Jun 9, 2013 at 4:25
  • Of course, don't forget to the read the StackOverflow explanation of Javascript Closures Commented Jun 9, 2013 at 4:40
  • possible duplicate of What do empty parentheses () after a function declaration do in javascript? Commented Jun 9, 2013 at 7:13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.