Novellizator
Novellizator

Reputation: 14883

Is every function a closure?

Just wondering, since closure is a function that has references to variables/methods outside it's definition. Every function closes over program's global variables (basically in every mainstream language, be it javascript/python/c/c+/whatever). So, consequently, every function is a closure?

Edit: let me reemphasize, I'm not talking only about closures in javascript but in a more general context

Upvotes: 10

Views: 2526

Answers (2)

georg
georg

Reputation: 215009

closure is a function that has references to variables/methods outside its definition

No, this is a "function with free variables", not a "closure".

To quote wikipedia

...a closure is only distinct from a function with free variables when outside of the scope of the non-local variables, otherwise the defining environment and the execution environment coincide and there is nothing to distinguish these (static and dynamic binding can't be distinguished because the names resolve to the same values).

In other words, in some context, a closure is a reference to a function that binds variables from another context. Otherwise, it wouldn't make sense to call it a "closure".

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074979

Yes, exactly. As you've identified, every function in JavaScript is a closure over at least one context: The global context. That's how/why global variables work in JavaScript.

We don't normally call them closures unless they close over some other context and actually make use of the fact that they do, but you're quite right that at a technical level, they all are.


Every function closes over program's global variables (basically in every mainstream language, be it javascript/c/c+/whatever).

I wouldn't generalize that far, no. Different languages have different ways of implementing global variables. Whether functions in those languages are all "closures" is probably open for debate, so I've restricted my answer above to JavaScript.

Upvotes: 9

Related Questions