0
0
Javascriptprogramming~3 mins

Why Closures in Javascript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your functions could remember secrets just for themselves, without anyone else knowing?

The Scenario

Imagine you want to keep track of how many times a button is clicked on a webpage. You try to do this by creating a global counter variable and updating it every time the button is clicked.

But what if you have many buttons and want each to keep its own count? You might try to create separate variables for each button manually.

The Problem

This manual way quickly becomes messy and confusing. You have to create many global variables, which can easily get mixed up or overwritten by mistake.

Also, it is hard to keep the counts private and safe from accidental changes elsewhere in your code.

The Solution

Closures let you create a special function that remembers the environment where it was created. This means you can keep each button's count private and safe inside its own function.

You don't need global variables or complicated tracking. The function itself holds the count and updates it whenever called.

Before vs After
Before
let count1 = 0;
function clickButton1() {
  count1++;
  console.log(count1);
}

let count2 = 0;
function clickButton2() {
  count2++;
  console.log(count2);
}
After
function createCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}

const clickButton1 = createCounter();
const clickButton2 = createCounter();
What It Enables

Closures enable you to write cleaner, safer code that keeps data private and remembers information between function calls.

Real Life Example

Think of a vending machine that remembers how many snacks it has sold without exposing that number to the outside world. Each vending machine keeps its own count safely inside.

Key Takeaways

Closures help keep data private inside functions.

They let functions remember information from when they were created.

This makes code easier to manage and less error-prone.