Javascript performance with closure

Viewed 2584
var name = function(n) {
    var digits = ['one','two','three','four'];
    return digits[n];
}

var namenew = (function() {
    digits = ['one','two','three','four'];
    return function(n) {
        return digits[n];
    }
}());

Both the versions result in the same output, however it is said that the second version is much faster than the first version.

As I understand, first version executes the function everytime where as the second version stores the result of execution. That is what confuses me as a functional/regular OOPS programmer.

How can one save a function with its inner context? What is happening under the hood? Can some one pls clarify?

2 Answers
Related