JSFiddle - React, Tailwind, and code Playground
JavaScript
// 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 pointer lives on outside of the scope of the function it was created in.
var digit_name = (function () {
var names = ['zero', 'one', 'two', 'three'];
return function (n) {
return names[n];
};
}());
console.log(digit_name(2)); // two