DEV Community

E_Chronosands::
E_Chronosands::

Posted on

Some basic understanding of closure🎈

About closure

Quoting Wikipedia: In computer science, a closure, also known as a lexical closure or function closure, is a technique for implementing lexical binding in programming languages ​​that support first-class functions. In implementation, a closure is a structure that stores a function (usually its entry address) and an associated environment (equivalent to a symbol lookup table).

The above description is very professional. I prefer to describe it this way: the ability of a function to remember and access variables in the scope in which it was defined. This characteristic is often used extensively in functional programming languages.

This type of code is typically written in JavaScript:

Why can the count variable still be accessed outside the outer function?
Because the outer function returns an inner function, and the inner function holds a reference to count, the local variable count will not be destroyed after outer finishes executing.

function outer() {
    let count = 0;

    return function inner() {
        count++;
        console.log(count);
    };
}

const fn = outer();

fn(); // 1
fn(); // 2
Enter fullscreen mode Exit fullscreen mode

This demonstrates an important function of closures: they extend the lifespan of variables. When an inner function references an outer variable, that variable cannot be released and must be moved to the heap to survive.

Closure -> A function carries the context in which it was defined

The most common use of closures

Data privatization

Using closures prevents external code from directly modifying a variable.

function createCounter() {
    let count = 0;

    return {
        inc() {
            count++;
        },
        get() {
            return count;
        }
    };
}

const c = createCounter();

c.inc();
c.inc();

console.log(c.get());
Enter fullscreen mode Exit fullscreen mode

Function Factory

function multiply(x) {
    return function(y) {
        return x * y;
    };
}

const double = multiply(2);

console.log(double(5));
Enter fullscreen mode Exit fullscreen mode

React hooks

A simple implementation of useState:

let hooks = [];
let currentIndex = 0;

function useState(initialValue) {
    const index = currentIndex;

    hooks[index] = hooks[index] ?? initialValue;

    function setState(newValue) {
        hooks[index] = newValue;
        render();
    }

    currentIndex++;

    return [hooks[index], setState];
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)