Mid From PDF JavaScript 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
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details