0

I have read the mega-thread on JavaScript closures, and there seems to be some discrepancy between the answers I have found, and was hoping I could get some further clarification.

Some of the answers within the thread states a closure is created when an inner function references variables from an outer function.

I found another answer that stated that this was a closure:

var a = 42;

function b() { return a; }

Notice how there is no inner/outer function, but simply just one function. The explanation that person gave was that a closure is when a function references an outer scope.

So my question is that is a closure created only when there are two functions (inner and outer), or when a function references an outer scope, which may or may not be a function (in this case, it simply is the top-level scope)?

the12
  • 2,395
  • 5
  • 19
  • 37

1 Answers1

2

Yes, a closure is a function - any function - with a reference to variables from an outer scope.

However, before ES6 closures could indeed only reference function scopes (even if there was a block scope) and the global scope. Given that closures over the global scope are pretty boring ones (you get the same behaviour in languages without lexical closures), most examples for closures will have nested functions.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375