What is a closure, and how/why would you use one?

Technology CommunityCategory: JavaScriptWhat is a closure, and how/why would you use one?
VietMX Staff asked 3 years ago

A closure is the combination of a function and the lexical environment within which that function was declared. The word “lexical” refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function’s variablesā€”scope chain even after the outer function has returned.

Why would you use one?

  • Data privacy / emulating private methods with closures. Commonly used in theĀ module pattern.
  • Partial applications or currying.