paint-brush
Javascript Closures: What Are They?by@sirius93
New Story

Javascript Closures: What Are They?

by Nandan KumarNovember 18th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Closures are a fundamental concept in JavaScript that enables powerful features like data privacy, state persistence, and functional programming. This blog will demystify closures with examples and practical use cases. Closures are created when a function **(inner function)** is defined inside another function ** (outer function) The inner function has access to the outer function's lexical scope **(variables)** even after it is executed.
featured image - Javascript Closures: What Are They?
Nandan Kumar HackerNoon profile picture

What Are Javascript Closures?

Closures are a fundamental concept in JavaScript that enables powerful features like data privacy, state persistence, and functional programming. This blog will demystify closures with examples and practical use cases.

When Are Closures Created?

Closures are created when a function (inner function) is defined inside another function (outer function). The inner function has access to the outer function's lexical scope (variables) even after the outer function is executed.

Lexical Scope in Javascript

Lexical scope means a function’s scope is determined by where it is written in the code, not where it is executed. This allows inner functions to access variables from their outer functions even if the outer function has already finished executing.

Usage

Closures are used for creating Private variables and persistent States (Cache, Memoisation, etc.).

Closures With Examples

A Simple counter

function Outer() {
    let count = 0; // count is a private variable
    return function inner() {
        count++; // count is updated every time inner is called
        return count; // the updated value of count is returned
    };
}

let Counter = Outer(); 
Counter(); // 1 (count starts at 0, incremented to 1)
Counter(); // 2 (incremented again)
Counter(); // 3


Building a cache leveraging closure

function ObjectCache() {
    let Obj = {}; // Obj acts as a private cache
    return function ObjectUpdate(key, value) {
        if (!Obj[key]) {
            Obj[key] = value; // Add key-value to cache if not already present
            return Obj; // Return updated cache
        } else {
            return new Error("Duplicate Key"); // Prevent overwriting
        }
    };
}

let cache = ObjectCache();
cache("a", "b"); // {a: 'b'}
cache("a", "c"); // Error: Duplicate Key
cache("alpha", "romeo"); // {a: 'b', alpha: 'romeo'}


Real World Examples

Event Listeners - Click Counter

function attachListener(element) {
    let count = 0;
    element.addEventListener('click', () => {
        count++;
        console.log(`Clicked ${count} times`);
    });
}


A Better Counter

const CounterModule = (() => {
    let count = 0;
    return {
        increment: () => ++count,
        reset: () => (count = 0),
        decrement: () => --count
    };
})();

CounterModule.increment(); // 1
CounterModule.increment(); // 2
CounterModule.decrement(); // 1
CounterModule.reset(); // 0


That’s all, folks! I hope you found this short blog on closures helpful. If you enjoyed this, check out more articles on my website, https://nandan.dev/


Feel free to comment, email me at [email protected], or connect with me on Twitter, Instagram, or GitHub. Don’t forget to subscribe to my newsletter for regular updates on JavaScript topics!


Twitter | Instagram | Github | Website