William C William C - 3 months ago 17
Javascript Question

JavaScript Closure: Returning a Function

I am working my way through a JavaScript lecture series by Douglas Crockford. I am confused by a code example he is showing to illustrate 'closure':



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

return function (n) {
return names[n];
};

}());

alert(digit_name(3));





How/why can
digit_name
take an argument when no parameter is specified in the definition (the outermost function)? How does the argument (in this case
3
) know to correspond to
n
within the inner function definition during invocation?

Answer

The digit_name stores the inner function returned by the outer function, which is an Immediately Executed Function Expression, where the inner function has the signature with one parameter and that's what is stored in the digit_name.

function (n) {
  return names[n];
}

Ultimately, the above will be the digit_name and the names is a private variable, which is bundled with the environment of digit_name. The concept of private variable is possible only using closures.

To make it clear, see this:

enter image description here

Comments