DEV Community

Discussion on: JavaScript Closures: Understanding Private Variables, Callbacks, and Memoization for Efficient Code

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

A closure is a function...

A closure is not a function. A closure is "the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)". This is a subtle distinction, but it needs to be made to stop people ending up with the mistaken belief that a closure is a special kind of function.

a closure is created when a function is defined inside another function,

This isn't correct. ALL functions have an associated closure, regardless of whether they were created inside another function.

From MDN:

In JavaScript, closures are created every time a function is created, at function creation time.

I'm not sure why so many people get this wrong.