Reading an example from a book, can someone explain how the function call to fibonacci takes in the argument ‘i’ when the function itself doesn’t declare any parameters?
var fibonacci = (function () {
var memo = [0, 1];
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
return fib;
}());
for(var i = 0; i <= 10; i += 1) {
document.writeln('// ' + i + ': ' + fibonacci(i));
}
You are creating a self-executing anonymous function
(function(){}());which inside it returns thefibfunction, which takes an argument.var fib = function(n){}…return fib;This system (returning a function from a self-executing anonymous function) allows for you to define variable in a local scope that can still be used by the returned function, but not by functions outside the scope. Here is an example.
This technique is called
closurein JavaScript. Read more about it on the MDN guide.