Closure là hàm 'nhớ' được biến từ lexical scope bên ngoài, ngay cả sau khi hàm ngoài đã return.
javascript
function makeCounter() {
let count = 0;
return () => ++count;
}
const c = makeCounter();
c(); // 1
c(); // 2Hàm trả về vẫn truy cập count.
Ứng dụng thực tế: private variables (encapsulation), factory functions, event handlers giữ state, debounce/throttle, React hooks (useState bên trong dùng closure).
A closure is a function that 'remembers' variables from its outer lexical scope, even after the outer function has returned.
javascript
function makeCounter() {
let count = 0;
return () => ++count;
}
const c = makeCounter();
c(); // 1
c(); // 2The returned function still accesses count.
Practical uses: private variables (encapsulation), factory functions, event handlers holding state, debounce/throttle, React hooks (useState internally uses closures).