Wednesday 18 June 2014

JavaScript Closures

Slow: digit_name creates the array each time it's invoked

var digit_name = function (n) {
var names = ['zero', 'one', 'two', 'three'];

return names[n];
};

console.log(digit_name(2)); // two

An example of a closure


Fast: digit_name immediately invokes a function and holds the result, a pointer to the array. This is a pointer to a variable that lives on outside of the scope of the function it was created in.


names is closed over the outer function.

var digit_name = (function () {
var names = ['zero', 'one', 'two', 'three'];

return function (n) {
return names[n];
};
}());

console.log(digit_name(2)); // two
JS Fiddle:  http://jsfiddle.net/stevenhollidge/22Ab7/

No comments:

Post a Comment