DEV Community

Discussion on: Lexical Variable Scoping with Javascript

Collapse
veevidify profile image
V

Things get crazy pretty quickly when it comes to scope and context, which is why most libraries / eslint rules enforce const usage and discourage mutating.

function createCounter() {
  let val = 0; // stateful value that lives in createCounter context
  function runCounter() {
    val ++; // mutate
    return val;
  }
  return runCounter;
}

const count = createCounter(); // count is a function that runs counter

const val1 = count(); // val1 == 1
const val2 = count(); // val2 == 2
const val3 = count(); // val3 == 3

const differentCount = createCounter(); // establish separate counter with separate state

const val4 = differentCount(); // val4 == 1
const val5 = differentCount(); // val5 == 2