Location, Location, Location
When code exists within a function it has local scope and is hidden from the code contained without. Working in the other direction, local code has access to the code in its outer scope.
Example - Bob Rules
Bob is my niece. She’s happy to share her corn snacks one at a time, but, and this is crucial if you don’t want to cross Bob, nobody else gets direct access to the packet, so it must absolutely not be left lying about in the public interface. Here’s Bob’s code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
If you run this code, you’ll ‘get’ one corn snack until Bob’s bag is empty. Nobody can go in and change the value of
cornSnackCount - i.e., nab all the virtual corn snacks on the sly - because
cornSnackCount is hidden inside a function. Bob is happy!
Happy But Confused
It mightn’t be immediately obvious how we achieve this state of corn snack affairs, so let’s talk it through…
In the above example, the outer function (
packetCornSnacks) returns its inner function (
bobShares), and the code at the bottom saves a reference to this nested function in the global environment, changing the normal flow of things. The nested function is created when its outer function is invoked, and it contains an inherent reference to where it was defined. So, even when the outer function has finished executing, a reference to its activation object remains in the global scope. The variable
cornSnackCount persists in this object.
The code at the very bottom calls
bobShares multiple times. Each time it is called, the function is the same, but its scope is changed because the value of
cornSnackCount defined in the outer function is decremented over invocations, until Bob’s bag is empty.
getSnacks is a closure of the interesting variety. Bob’s packet of corn snacks can’t be interfered with, but its value is remembered across invocations of
This has been a particularly tricky topic to approach as a newbie coder, and I’d welcome any pointers that could provide further insight.