syntax Copy
var variableName = value;example Copy
function demo() {
if (true ) {
var leaked = "visible outside block" ;
}
console.log(leaked);
}
demo();output
"visible outside block"Note Function-scoped, not block-scoped. Hoisted to the top of the function. Avoid in modern code -- use let or const instead.
syntax Copy
function outer() {
let state = value;
return function inner() { /* access state */ };
}example Copy
function createCounter(initial = 0 ) {
let count = initial;
return {
increment() { return ++count; },
decrement() { return
value() { return count; },
};
}
const counter = createCounter(10 );
console.log(counter.increment());
console.log(counter.increment());
console.log(counter.value()); Note A closure is a function that retains access to its outer scope's variables even after the outer function has returned. Fundamental for data privacy and stateful functions.