We often call arrow functions “closures”, but that is a misnomer. Arrow functions can be closures, but not always. A normal function can be a closure too!
A closure closes over syntactic scope.
closureFunction close over
Closures are weird because they can close over local variables.
The global variable
a is pretty simple. Any function can access it.
a exists for the entire lifecycle of the program. But what about
What is the lifecycle of the local variable
b? Naively it may seem like
b should exist for as long as the invocation of
foo, but the
bar closure uses
b is removed after the call to
bar wouldn't be able to change
The answer is
b exists until all references to it are garbage collected. This means it is not possible to implement closures without a garbage collector.
Isn’t that weird? Something as simple as closures requires a full-on garbage collector.
Async/await (which are just promises) and callbacks are required to work with the event loop.
Callbacks are just closures and the promise API use closures.
But what about languages that don’t have closures? Surely function pointers are a sufficient alternative.
Function pointers in systems programming languages like Zig may seem like closures as one can pass function pointers just like closures.
But there is no way for function pointers to close over local variables.
This is why for function pointers, there is often a context object passed to the callback.
Aside: This is a contrived example; one wouldn’t use a function pointer for this use case.
Do you dream in closures? We’d like to hear from you, Battlefy is hiring.