Shallower on Closures

After coming back to some exercises on exercism involving closures, I quickly learned that my fundamental understanding of them was not what I'd believed. Whether this is due to a month passing since I visited the subject or the concussion I sustained in a recent car accident, I don't know.

In any case, I'm going to write (with likely overlap from previous entries) some very fundamental Closures examples, in the hopes to both document this and reference it later.

Consider the following code:

let runningTotal = 0;
const addToTotal = (num1) => {runningTotal += num1};

const funcBuilder = (unaryFunc) => {
     return (arg) => {unaryFunc(arg)}
    }

const addThem = funcBuilder(addToTotal);

addThem(6); //6
addThem(2); //8

In this simple example, a given number is added to runningTotal via an anonymous function returned by funcBuilder(). This doesn't make use of closures. If you have multiple totals to track, this approach isn't effective, as each successive call will still use the original runningTotal.

const addThem2 = funcBuilder(addToTotal);
addThem2(4); //12, added to existing runningTotal

You can seen an example pulled from the javascript.info tutorial on closure/Variable scope that illustrates use of closure to instantiate/track separate running totals:

function makeCounter() {
  let count = 0;

  return function() {
    return count++;
  };
}

let counter = makeCounter();
let counter2 = makeCounter();

counter and counter2 will increment independent instances of the count variable. The count variables in the above example will be tracked by Javascript, and not cleaned up until all instances of the returned anonymous functions no longer reference this variable.