William C William C - 1 year ago 93
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];



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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download