Search code examples
javascript

Javascript Memoization Explanation?


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));
}

Solution

  • You are creating a self-executing anonymous function (function(){}()); which inside it returns the fib function, which takes an argument. var fib = function(n){} ... return fib;

    var fibonacci = (function () { // Self-executing anonymous function
        var memo = [0, 1];         // local variable within anonymous function
        var fib = function (n) {   // actual fib function (takes one argument)
            var result = memo[n];  // fib function is now bound to the memo variable from the outer scope and a closure is formed
            if (typeof result !== 'number') {
                result = fib(n - 1) + fib(n - 2);
                memo[n] = result;
            }
            return result;
        };
        return fib; // return fib (fibonacci is now set to the function fib defined above, which takes one argument)
    }());
    

    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 closure in JavaScript. Read more about it on the MDN guide.