Codacoda
Back to Academy

functional programming

Closures

A closure is a function that captures and remembers variables from its enclosing scope, even after that scope has finished executing. Think of it like a backpack a function carries — wherever the function goes, it still has access to the items it packed when it was created. Closures enable powerful patterns like private state, factory functions, and memoization without relying on global variables or classes.

Use Cases

  • Encapsulating private state without classes (counters, rate limiters, caches)
  • Creating factory functions that produce pre-configured behavior
  • Implementing memoization caches that persist across function calls
  • Building middleware or decorators that capture configuration at creation time

Implementation

Output

Click "Run Code" to see output...