Bob Myers
2 min readAug 24, 2018

--

The notion of closure in JS can be expressed in a single sentence: functions have access to variables in lexically enclosing scopes, even after those functions are returned to the outside world. Yes, to understand this definition, you have to define “lexically”, but that should not be very hard.

If a function does not use a variable from an enclosing scope, and/or if that function is not returned in some fashion to the outside world, or if the immediately enclosing scope is the global scope, then although it might be theoretically correct to call it a “closure”, it is meaningless (and confusing) to do so.

It’s useful to be very clear on the exact meaning of the word “close” and “closure”. The original meaning of the word was related to the notion of closing, in the sense that a particular function closes over a variable in an enclosing scope. So to be precise, the function itself is not a “closure”, contrary to common wisdom and the misinformation you perpetuate. The “closure” involved is the phenomenon of the “closing” of the function over the variable in question.

The term “closure function” which you use is non-standard and confusing.

More basically, your entire example misses the basic point of closures. All you show is an internal function, which of course shares (has access to) variables in the parent function. You don’t show the essential point of closures, which is when the internal function is exported somehow, as in:

function adder(val) {
return function(to) {
return val + to;
};
}

where the internal function is returned, and maintains access to (closes over) val in its internal state, to which the internal function has access even after being returned, allowing it be used in situations such as

const add6 = adder(6);
console.log(add6(42)); // yields 48

--

--

Bob Myers
Bob Myers

Written by Bob Myers

Technologist, writer, Japanologist

No responses yet