AI News Hub Logo

AI News Hub

Some basic understanding of closure🎈

DEV Community
E_Chronosands::

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? function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 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 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()); function multiply(x) { return function(y) { return x * y; }; } const double = multiply(2); console.log(double(5)); 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]; }