Example 1: Getting digit name
The goal is to read from an array and display the result. The first implementation is to put everything in Global namespace.
Above solution works. However creating a global variable
names is not a good thing. You should create as less global variables as possible.
Moving to a function
Next step is to move the code to a function. In this case we will not have any global variable.
The above solution is very slow. Every single time the function is called the whole array is loaded. This solution works and most of the developers will settle with this one. However Closure can provide a better solution.
Better solution with Closure
Note that at after declaring the function the function is also getting invoked. This is a case of self invoking function. You can find out more about self invoking function here .
Example 2: Getters and Setters
Developers deal with getters and setters all the time. However creating a good getter and setter could be a little tricky. Here is one implementation
Above solution works and it’s nicely done.
Let’s look at another implementation.
This is a simple case of serially iterating through the items provided but the logic of deciding next element can be complex and it can be private.