Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is every function a closure?

Tags:

closures

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

like image 411
Novellizator Avatar asked Feb 01 '16 12:02

Novellizator


2 Answers

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.

like image 137
2 revs Avatar answered Oct 13 '22 12:10

2 revs


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".

like image 26
georg Avatar answered Oct 13 '22 13:10

georg