JavaScript Closure Explained with a Real React Example (Movie Ticket Booking)

JavaScript Closures in React – Movie Ticket Booking (Silver & Gold)

In this blog, we will understand JavaScript closures using very small code snippets, and then connect it to a real React movie ticket booking screen with Silver & Gold seats. We’ll also use the useState lazy initializer pattern.

Closures are not magic. They are just functions that remember some values. Let’s prove it with small examples and then build a real UI idea.

🎥 Watch the Video Explanation

I have a full video on my YouTube channel where I explain this same concept with live coding. You can watch it here:

You can also visit my channel: @CodeWithSanyogita

1. Start with a Tiny Closure

First, forget React. Let’s build the smallest closure example.

Goal: Create a function that increases a counter every time we call it.

// Step 1: Outer function
function createCounter() {
  let count = 0;    // local variable

  // Step 2: Return inner function
  return function () {
    count = count + 1;
    return count;
  };
}

// Step 3: Use it
const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
  

Why is this a closure?

  • count is inside createCounter.
  • We return an inner function that uses count.
  • Even after createCounter() finished, the inner function still remembers the last value of count.
Definition to remember:
A closure is a function that remembers variables from the place where it was created.

2. Add a Label: Silver & Gold Style

Now let’s add a label. This will help us later for Silver and Gold tickets.


function createLabeledCounter(label) {
  let count = 0;

  return function () {
    count = count + 1;
    console.log(label, "count is", count);
    return count;
  };
}

const silverCounter = createLabeledCounter("SILVER");
const goldCounter   = createLabeledCounter("GOLD");

silverCounter(); // "SILVER count is 1"
silverCounter(); // "SILVER count is 2"
goldCounter();   // "GOLD count is 1"
  

Each counter:

  • Has its own count variable.
  • Remembers that count through the inner function.
  • Is a separate closure

👩‍💻 Written by Code With Sanyogita

Frontend Developer & content creator sharing beginner-friendly tutorials on React, JavaScript, and Web Development.

If this post helped you, consider subscribing on YouTube for more real-world coding examples 🚀

Comments

Popular posts from this blog

React Debouncing Explained with Real Search API Example (JavaScript)

React Keys: Index vs ID Explained (Delete Item Bug with Example)