DEV Community

Discussion on: What is a Closure? 🤔

Collapse
 
pentacular profile image
pentacular

three very important and distinct types of scope in JavaScript: local, global and lexical.

Saying 'distinct' seems to imply that local and global scopes aren't lexical, which might be confusing.

All scopes related to mapping names to entities based on their placement in the code are lexical.

The beauty of lexical scoping is that the value of a variable is determined by its placement in the code.

It isn't the value of the variable that's determined by its placement.

It's the variable that a given name refers to that is determined by its placement in the code.

Closure is a function that can access its lexical scope, even when that function is being invoked later.

Rather, a closure maintains the variables that it references in its lexical scope throughout its lifetime, rather than the variables disappearing when the function call they were established as local variables of returns.

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

I think it's important to distinguish between the lexical environment (which is essentially a representation of the source code) and the dynamic environment that a function invocation executes within.

This is important because while there may be only one variable in the lexical environment, it may have many distinct instances in the dynamic environment.

Consider

const createCounter = () => {
  let counter = 0;
  return () => counter++;
}

const counter1 = createCounter();
const counter2 = createCounter();

After execution we end up with two distinct instances of counter in existence, although the lexical environment containing counter is no-longer in scope for anything. :)