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.

Frequently asked questions

How does JavaScript handle function scope?
JavaScript covers this with 2 copy-ready snippets on this page. The "var Declaration (Legacy)" snippet in JavaScript uses `var variableName = value;`.
Which code does the JavaScript example use?
The "var Declaration (Legacy)" snippet uses `var variableName = value;`, from the Variables & Constants section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "function scope"?
Besides "var Declaration (Legacy)", this page also shows "Closures".
Is there anything to watch out for?
Yes. For "var Declaration (Legacy)": Function-scoped, not block-scoped. Hoisted to the top of the function. Avoid in modern code -- use let or const instead.