Closures

Intermediate·25 min read·Lesson 3 of 8·Not Started

A closure is the combination of a function bundled together with references to its lexical environment. In other words, a closure gives you access to an outer function's scope from an inner function.

How Closures Work

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to resolve variables that are not in the local scope.

Common Use Cases

  • Data encapsulation and privacy
  • Function factories
  • Event handlers and callbacks
  • Partial application and currying

Interview Tip

Closures are one of the most frequently tested concepts in JavaScript interviews. Be prepared to explain how closures work with loops, and understand the classic setTimeout closure problem.