A closure adalah fungsi sing diikat bareng karo referensi marang variabel saka lingkungan leksial (scope) ing saubengé. Merga closure, fungsi inner tetep bisa ngakses variabel fungsi outer sanajan fungsi outer wis bali.
js
function makeCounter() {
let count = 0; // private variable, captured by the closure
return {
inc: () => ++count, // each closure "remembers" its own count
get: () => count,
};
}
const a = makeCounter();
const b = makeCounter(); // independent closure — separate count
a.inc(); a.inc(); // a.get() → 2
b.inc(); // b.get() → 1 (a is untouched)
count ora bisa diakses saka luar — mung inc/get sing bisa neoni. Iku data privacy sing dibangun saka closure. Lan saben panggilan makeCounter() nggawe scope anyar sing terpisah.
Kasalahan loop klasik
js
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // prints 3, 3, 3 — all share one `i`
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // prints 0, 1, 2 — `let` is per-iteration
}
Karo var, saben callback nutup luwih i sing padha (sing dadi 3 nalika bakal dilakokke). let nggawe binding anyar saben iterasi.
Mengapa penting
Closures nduweni kakuwatan module privacy, memoization, currying, event handlers/callbacks sing ngengo-ingat state, lan persis carane React hooks (useState) tetepake nilai antarane renders.
