1

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?

1
  • When it's defined it's an IIFE. Commented Aug 10, 2016 at 13:46

3 Answers 3

2

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

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

Comments

0

Theres a self calling, anonymous function (function(){})() . So digit_name is not the function, its what the function outputs in is return statement.So this happens inside the browser:

var digit_name=(function(){})();
var digit_name=function(n){}

Comments

0

The outer function is an IIFE, an immediately-invoked function expression. That function is ran when the script starts and therefore the inner function returned by the IIFE is what is assigned to digit_name.

The "magic" of the closure if that this inner function still has access to everything in the closure (such as the names array).

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

2 Comments

...and the inner function returns a function that takes a parameter.
Yes, I should have specified that the inner function is the one that is returned.

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.