I have come across this javascript code.
var digit_name = function() {
var names = ['zero', 'one','two'];
return function(n) {
return names[n];
};
}();
alert(digit_name(1));
The output is one. I understand that the inner function is being assigned to the variable digit_name. What is the need for adding parentheses in the 6th line after the code of outer function. Can anyone tell what exactly is going on?
The ending
()you see make that outer function execute immediately. Sodigit_nameends up storing the resulting inner function, as opposed to a pointer to the outer function.For more information see: What is the purpose of a self executing function in javascript?