Skip to content Skip to sidebar Skip to footer

Lexical Environment Example Explanation

I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far: function makeCounter() { function counter() {

Solution 1:

I think using a property of the function object is quite confusing here, especially if you want to learn about lexical environments. A better example might be the difference between

function makeCounter() {
  var count = 0;
  function counter() {
    return count++;
  }
  return counter;
}

and

var count = 0;
function makeCounter() {
  function counter() {
    return count++;
  }
  return counter;
}

where it is more obvious how many count variables there are, when they are created, and in which scope they live. Of course it works the same with the indirection through the counter vs makeCounter variables (that get initialised with function objects), which live in the same scopes as count does in my examples.

Admittedly, makeCounter.count = 0 should better be outside of makeCounter, as otherwise the behaviour of resetting the global count will get really confusing. The exact property-less code corresponding to yours would be

function makeCounter() {
  var count;
  function counter() {
    return count++;
  }
  count = 0;
  return counter;
}

vs

var count;
function makeCounter() {
  function counter() {
    return count++;
  }
  count = 0;
  return counter;
}

Solution 2:

The function counter and counter.count are defined new in the function scope of makeCounter in each call. makeCounter.count is defined once only for the global scope.

Solution 3:

What I don't understand is if I am using the property of the function makeCounter I am still incrementing the makeCounter.count if I assign it to new variables:

makeCounter is available in the scope in which it is defined and inside makeCounter definition as well.

So, since makeCounter.count is not scoped exclusively local to makeCounter function definition, so both counter and counter1 has access to the same reference of makeCounter.count.

Solution 4:

New lexical scope is created every time and when makeCounter() returns it remembers count value in clojure. In simple words, it's a language feature that allows functions to remember variables from scope where a function was defined.

It allows to make 'private' like variables in Javascript.

Post a Comment for "Lexical Environment Example Explanation"