Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Understand Closures for Scope and Privacy

- 07.07.26 - ErcanOPAK

🔒 Closures = Scope + Privacy

Variables leak globally? Closures create private scope. Data privacy, factory functions, state management.

📝 Closure Examples

// Basic closure
function outer() {
    let privateVar = 'secret';
    
    return function inner() {
        console.log(privateVar); // 'secret'
    };
}
const closure = outer();
closure(); // Uses privateVar

// Private counter
function createCounter() {
    let count = 0;
    
    return {
        increment: function() {
            count++;
            return count;
        },
        decrement: function() {
            count--;
            return count;
        },
        getValue: function() {
            return count;
        }
    };
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
console.log(counter.getValue()); // 2

// Factory functions
function createUser(name) {
    let _name = name;
    let _age = 0;
    
    return {
        getName: function() {
            return _name;
        },
        setName: function(newName) {
            _name = newName;
        },
        getAge: function() {
            return _age;
        },
        setAge: function(newAge) {
            if (newAge > 0) {
                _age = newAge;
            }
        }
    };
}
const user = createUser('Alice');
console.log(user.getName()); // 'Alice'

🎯 Advanced Closure Patterns

// Memoization
function memoize(fn) {
    const cache = {};
    
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache[key] === undefined) {
            cache[key] = fn(...args);
        }
        return cache[key];
    };
}
const expensiveFn = (n) => n * n;
const memoized = memoize(expensiveFn);
console.log(memoized(5)); // Computed
console.log(memoized(5)); // From cache

// Module pattern
const Calculator = (function() {
    // Private members
    let result = 0;
    
    function validate(value) {
        return typeof value === 'number';
    }
    
    return {
        // Public methods
        add: function(value) {
            if (validate(value)) {
                result += value;
            }
            return this;
        },
        subtract: function(value) {
            if (validate(value)) {
                result -= value;
            }
            return this;
        },
        getResult: function() {
            return result;
        },
        reset: function() {
            result = 0;
            return this;
        }
    };
})();

Calculator.add(5).subtract(2).add(10);
console.log(Calculator.getResult()); // 13

// Partial application
function multiply(a) {
    return function(b) {
        return a * b;
    };
}
const double = multiply(2);
const triple = multiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15

💡 Closure Use Cases

  • Private variables (data privacy)
  • Factory functions
  • State management
  • Memoization (caching)
  • Event handlers with state

“Closures enable privacy and state. Private variables, factory functions. Essential for JavaScript mastery.”

— JavaScript Developer

Related posts:

AJAX — 204 Responses Break JSON Parsing

JavaScript: Using the Proxy API for State Management

JavaScript: Master the Spread Operator (...)

Post Views: 1

Post navigation

HTML: Implement Accessibility (A11y) Best Practices
Ajax: Understand CORS for Cross-Origin Requests

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (597)
  • Add Constraint to SQL Table to ensure email contains @ (582)
  • Average of all values in a column that are not zero in SQL (545)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (512)
  • Find numbers with more than two decimal places in SQL (460)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com