Function scope

2 snippets in JavaScript

JSJavaScript

var Declaration (Legacy)

JS · Variables & Constants
syntax
var variableName = value;
example
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.

Closures

JS · Functions
syntax
function outer() {
  let state = value;
  return function inner() { /* access state */ };
}
example
function createCounter(initial = 0) {
  let count = initial;
  return {
    increment() { return ++count; },
    decrement() { return --count; },
    value()     { return count; },
  };
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.increment()); // 12
console.log(counter.value());     // 12

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.