Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 40

Closures for Encapsulation and Private Variables

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Welcome back.

In our last lesson, we took a deep dive into the mechanics of closures. We learned that a closure is the combination of a function and the lexical environment where it was declared, which allows the function to "remember" its surrounding state. You saw how this works with hidden properties and lexical environments that defy garbage collection.

Today, we move from the how to the why. This lesson focuses on the practical power of closures. You'll learn how to harness them to create and use closures to encapsulate state and create private variables. This isn't just a theoretical exercise; it's a fundamental pattern for writing organized, secure, and reusable code, a skill that is absolutely essential for building robust applications with tools like Next.js and TypeScript.

The Problem: Unprotected Global State

Before we see the solution, let's understand the problem. Imagine we want a simple counter. Without closures, our first instinct might be to use a global variable.

let count = 0; // A global variable

function incrementCounter() {
  count++;
  console.log(`The count is now ${count}`);
}

incrementCounter(); // The count is now 1
incrementCounter(); // The count is now 2

This works, but it has a major flaw. Since count is global, any part of our program can change it at any time, often unintentionally.

// Some other part of the code, maybe written by another developer...
count = -500; // This completely messes up our counter!

incrementCounter(); // The count is now -499. This is not what we wanted.

This is where closures become our primary tool for protecting our data.


The Solution: Encapsulation with Closures

Encapsulation is a core programming concept that means bundling data (the state) together with the methods (functions) that operate on that data. A closure is JavaScript's natural mechanism for achieving this.

Let's refactor our counter to use a closure:

function createCounter() {
  let count = 0; // 'count' is now private to the createCounter scope

  // The returned function is a closure
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();

console.log(counter()); // Output: 1
console.log(counter()); // Output: 2

// Now, can we mess with 'count' from the outside?
// count = 99; // This would cause a "ReferenceError: count is not defined"
// console.log(counter.count); // This is 'undefined'. We can't access it.

Here, the count variable is completely protected. It lives inside the closure's "backpack" (the remembered lexical environment of createCounter) and is only accessible to the function we returned. We have successfully created a private variable.

To learn more about the benefits of this pattern, let's read a short article.

Comprehensive Guide to Closures in JavaScript and TypeScript

This guide provides clear examples of using closures for data privacy and state management. It reinforces the concepts we've just discussed.

Please read the following sections from the article by Saeid Khoorani: Introduction and What is a Closure?: A quick refresher. Importance of Closures: Focus on points 1 (Data Encapsulation) and 2 (State Management). -Data Encapsulation and Privacy: Read this section and study the createSecret example. -Maintaining State Across Function Calls: Read this section and study the createCounter example. These sections explain how closures are the key to creating private variables and managing state without polluting the global scope.


Creating Independent States

A crucial feature of this pattern is that every time you call the "factory" function (createCounter), you create a new, independent closure with its own private state.

Watch this fantastic visualization of how two separate calls to a factory function result in two independent counters, each with its own preserved environment.

JavaScript Visualized - Closures

This video from Lydia Hallie's 'JavaScript Visualized' series perfectly illustrates how separate closures maintain their own unique state.

Watch the segment from 06:41 to 08:37. Notice how counter1 and counter2 are created from separate calls to createCounter. The animation clearly shows that each gets its own environment record, so incrementing one does not affect the other.

This is a powerful concept. It allows you to create multiple, independent instances of a component, each managing its own state, which is a pattern you will use constantly in frameworks like React and Next.js.

const counterA = createCounter();
const counterB = createCounter();

console.log('Counter A:', counterA()); // Counter A: 1
console.log('Counter A:', counterA()); // Counter A: 2
console.log('Counter B:', counterB()); // Counter B: 1 (Completely independent!)

The Module Pattern: A Public API for Private Data

So far, we've returned a single function. But what if we want to perform multiple operations on our private state? We can do this by returning an object containing several functions. These functions all share the same closure, giving them all access to the same private state. This is known as the Module Pattern.

JavaScript Closure Example: Private Counter
This image illustrates the Module Pattern. The `createCounter` function returns an object with `increment` and `reset` methods. Both methods have access to the private `count` variable within the closure.

Let's build the counter from the image above:

function createCounterModule() {
  let count = 0; // Private state

  // Return an object with our "public" methods
  return {
    increment: function() {
      count++;
      console.log(count);
    },
    decrement: function() {
      count--;
      console.log(count);
    },
    getCount: function() {
      return count;
    }
  };
}

const counterModule = createCounterModule();

counterModule.increment(); // logs: 1
counterModule.increment(); // logs: 2
counterModule.decrement(); // logs: 1

// We can get the value, but we still can't change it directly
console.log(`The current count is ${counterModule.getCount()}`); // The current count is 1

// counterModule.count = 100; // This has no effect on the private 'count'
counterModule.increment(); // logs: 2

We've created a self-contained "module" with:

  • Private state: The count variable.
  • Public API: The increment, decrement, and getCount methods, which are the only ways to interact with that state.
Test your understanding!

Your turn to build a module! Create a function called createWallet(initialBalance).

  • It should accept an initialBalance.
  • It should contain a private balance variable.
  • It should return an object with three methods:
    1. deposit(amount): adds to the balance.
    2. withdraw(amount): subtracts from the balance.
    3. checkBalance(): returns the current balance.

Make sure that you cannot directly access or modify the balance from outside the module.

Show answer

Here's one way to implement the createWallet function:

function createWallet(initialBalance = 0) {
  let balance = initialBalance; // Private state

  return {
    deposit: function(amount) {
      if (amount > 0) {
        balance += amount;
      }
      console.log(`Deposited ${amount}. New balance: ${balance}`);
    },
    withdraw: function(amount) {
      if (amount > 0 && amount <= balance) {
        balance -= amount;
        console.log(`Withdrew ${amount}. New balance: ${balance}`);
      } else {
        console.log(`Insufficient funds or invalid amount for withdrawal.`);
      }
    },
    checkBalance: function() {
      return balance;
    }
  };
}

// Usage:
const myWallet = createWallet(100);

console.log(myWallet.checkBalance()); // 100

myWallet.deposit(50); // Deposited 50. New balance: 150
myWallet.withdraw(20); // Withdrew 20. New balance: 130
myWallet.withdraw(200); // Insufficient funds...

// You still can't access the balance directly:
console.log(myWallet.balance); // undefined

Conclusion

Today you've put the theory of closures into practice. You've seen that they are not just a quirky language feature, but the primary tool in JavaScript for creating privacy and building modular, stateful components.

Key Takeaways:

  • Encapsulation: Closures allow you to bundle private state (variables) with public methods (functions) that operate on that state.
  • Private Variables: Any variable declared in an outer function is private to the inner functions that form a closure. It cannot be accessed from the outside.
  • Stateful Functions: Closures give functions "memory," allowing them to maintain state across multiple calls without polluting the global scope.
  • Module Pattern: By returning an object of methods from a function, you can create a clean, reusable module with a public API and private implementation details.
  • Independent Instances: Each call to a factory function creates a new, independent closure with its own encapsulated state.

Next Up:

While closures are incredibly powerful, they can sometimes lead to unexpected behavior, especially in loops or when memory is a concern. In our next lesson, we will identify common scope-related bugs and apply best practices to avoid them, ensuring you can use closures confidently and correctly.