I never understood JavaScript closures

2 comments · 43% upvoted · source · other discussions

comments

seands

I think of them as nested functions with the scoping rules one would expect. Is there anything more to them?

njiv

they are actually objects (with a single method), functions don't have any state, closures have, e.g.

function getCounter() { let cur = 0 return function clos() { return cur++; } }

Here clos has a state field, in fact, compilers convert functions into objects using so-called Closure Conversion Pass, it is a classical transform, you can google it if interested.