Mid JavaScript

What are common use cases of closures?

  • Data privacy / encapsulation
  • Callbacks and event handlers
  • Memoization / caching
  • Module pattern for structuring code

Example – private counter:

function createCounter() {

let count = 0; // private variable

return {

increment: () => ++count,

decrement: () => --count

const counter = createCounter();

console.log(counter.increment()); // 1

console.log(counter.decrement()); // 0

More from JavaScript Tutorial

All questions for this course