Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JS Puzzles · Const

Function Scope

Function scope limits a function's local declarations to that function. Nested functions can access enclosing scopes, creating a scope chain where nearer bindings shadow outer ones.

How it works

A function creates its own scope. Names declared inside it are unavailable to outside code, while the function can read names from surrounding scopes. Nested functions can retain access to enclosing bindings, forming a scope chain.

Syntax

function functionName(parameters) { statements }

Key points

  • Each function creates a private variable scope; declarations inside it are not directly accessible from outside.
  • Code inside a function can access names available in its surrounding scopes.
  • Nested functions can use bindings from their parent function.
  • Scope access is one-way: outer code cannot see declarations that exist only in an inner function.
  • With multiple nested functions, lookup follows a chain of enclosing scopes.
  • If several scopes define the same name, the innermost declaration takes precedence.

Common mistakes

  • An inner function can read variables from enclosing scopes, but an enclosing function cannot read variables declared only inside the inner function.
  • When names conflict, the nearest enclosing declaration wins because lookup proceeds from the innermost scope outward.

Example: A closure retains function scope

function makeCounter() {
  let count = 0;
  return () => ++count;
}

const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2

The returned function keeps access to the outer function's local binding.

When to use it

Encapsulation

Hide implementation details and temporary state inside a function.

Closures

Build callbacks that retain access to variables from their creation context.

Nested functions

Resolve names across nested functions using lexical scope.

  • scope chain
  • closures
  • nested functions
  • function declarations
  • function expressions

Source: Functions - JavaScript | MDN. Checked 2026-10-15.