Scope & Closures
Scope
- Global — bisa diakses di mana saja
- Function — hanya di dalam fungsi
- Block — di dalam {} (let/const)
Closures
Closure adalah fungsi yang "mengingat" variabel dari scope di mana ia dibuat, bahkan setelah scope tersebut selesai.
Closure adalah fungsi yang "mengingat" variabel dari scope di mana ia dibuat, bahkan setelah scope tersebut selesai.
let result = "";
// Block scope
{ let x = 10; result += "Inside block: x = "+x+"
"; }
result += "Outside block: x is not accessible
";
// Closure - counter
function makeCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
const counter = makeCounter();
counter.increment();
counter.increment();
counter.increment();
result += "// Closure Counter
";
result += "After 3 increments: " + counter.getCount() + "
";
result += "count variable is private!
";
// Closure - greeting factory
function greetIn(lang) {
const greetings = { id: "Halo", en: "Hello", jp: "Konnichiwa" };
return (name) => greetings[lang] + ", " + name + "!";
}
const greetID = greetIn("id");
const greetEN = greetIn("en");
result += "greetID('Ali') → " + greetID("Ali") + "
";
result += "greetEN('Ali') → " + greetEN("Ali");
document.getElementById('output').innerHTML = result;