Skip to primary content
Web Technical Tutorial

JavaScript Closures: Lexical Scoping, Encapsulation & Memory Lifecycle

Master closures in JavaScript: lexical scope, function factories, data encapsulation, private variables, and memory management.

Web
function createBankAccount(initialBalance) {
    let balance = initialBalance; // Private state protected by closure

    return {
        deposit(amount) {
            if (amount > 0) balance += amount;
            return balance;
        },
        withdraw(amount) {
            if (amount > 0 && amount <= balance) balance -= amount;
            return balance;
        },
        getBalance() {
            return balance;
        }
    };
}

const account = createBankAccount(5000);
account.deposit(2500);
console.log("Balance:", account.getBalance()); // 7500
// balance variable is inaccessible directly from global scope!

1. What is a Closure?

A closure is the combination of a function bundled together with references to its surrounding lexical environment. In JavaScript, closures are created every time a function is created at function creation time.

2. Data Encapsulation & Private Variables

Before ES2022 private class fields (#field), closures were the primary mechanism for implementing data hiding and private variables in JavaScript software design.

Key Engineering Takeaways
  • A closure retains access to outer variables even after the outer function has returned.
  • Closures enable module patterns, currying, and memoization techniques.
  • Beware of unintentionally retaining large objects in closures, which can lead to memory retention.

Frequently Asked Questions

Do closures consume more memory?
Yes, variables referenced by an active closure cannot be garbage collected while the inner function remains reachable.
Master This in Our Ghaziabad Coding Labs

Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.

Explore Related Course Call 7503962162
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details