Skip to content
jshacks.dev
Fundamentals

Block Scope vs Function Scope in JavaScript Explained

Function scope ends at the function and block scope at the nearest braces. See which keywords use which, how shadowing works and the switch case trap.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, Node.js, TypeScript and npm logos.

When a variable is "not defined" in a place where you are sure you declared it, the problem is almost always scope: you declared it in a block, and used it outside. JavaScript has two kinds of local scope, and which one applies depends on the keyword you used, not on where you typed it. The rules are short once you separate them. This post lists what creates each kind of scope, shows var leaking and let not, then covers shadowing, the switch trap and a few older features that behave differently. Examples run on Node.js 24 as ES modules. The keywords themselves are compared in var, let and const, and the bigger picture of scope and closures is in the guide to scope, hoisting and closures.

What makes a scope

A scope is a region of source where a name is visible. JavaScript has these, from outermost to innermost: the global scope, a module's scope, a function's scope and a block's scope. Name lookup starts at the innermost and walks outward, a process described in the post on the scope chain.

ConstructCreatesVisible to
A module fileModule scopevar, let, const, class, function declarations at the top level
A functionFunction scopeIts parameters, var and inner let and const
if, for, while, try, catch, finally, switchBlock scopeOnly let, const, class declared inside
A bare { ... }Block scopeOnly let, const, class declared inside
A for headA scope for the headlet or const declared in the parentheses

The key sentence is in the last column of the second row. A function holds everything declared inside it, including var inside nested blocks. A block holds only the block-scoped kinds.

The leaking var

The clearest demonstration is the same code with each keyword.

JavaScript
function scopes() {
  if (true) {
    var fromVar = "var";
    let fromLet = "let";
    const fromConst = "const";
  }

  console.log(typeof fromVar);
  console.log(typeof fromLet);
  console.log(typeof fromConst);

  for (var counter = 0; counter < 3; counter++) {}
  console.log(counter);

  for (let index = 0; index < 3; index++) {}
  console.log(typeof index);
}

scopes();
Text
string
undefined
undefined
3
undefined

fromVar is visible after the if block, because var belongs to the function. The other two do not exist there. The same split holds for loops: counter is still there after the loop and holds the final value, and index is gone. That leftover value is a real source of bugs, since a later line can read a loop counter by accident.

A block does not need a statement

You can write braces by themselves to create a scope. It is useful to limit a temporary name, and it is the way to give each case its own scope.

JavaScript
const total = 10;

{
  const total = 99;
  const only = "inside";
  console.log(total, only);
}

console.log(total);
console.log(typeof only);
Text
99 inside
10
undefined

Inside the braces, total is a new constant that hides the outer one, and only exists for those lines alone. After the block, the outer total is untouched.

Shadowing

A declaration in an inner scope with the same name as an outer one shadows it. The outer binding is not changed, and it is hidden only while the inner scope is active.

JavaScript
const level = "outer";

function show() {
  const level = "function";
  if (true) {
    const level = "block";
    console.log(level);
  }
  console.log(level);
}

show();
console.log(level);
Text
block
function
outer

Three different bindings share one name, and each line prints the nearest one. Shadowing is legal and sometimes intentional, but it is a common source of confusion, and ESLint's no-shadow rule flags it. A parameter that shadows a module-level variable is the usual accident, because an edit that renames one can leave the other. We turn the rule on in new code and fix the warnings in the files we touch.

A related trap is the declaration that shadows itself in its own initializer.

JavaScript
const value = "outer";

function broken() {
  try {
    const value = value + "!";
    return value;
  } catch (error) {
    return `${error.name}: ${error.message}`;
  }
}

console.log(broken());
Text
ReferenceError: Cannot access 'value' before initialization

The initializer value + "!" refers to the new value, which is in its temporal dead zone, not the outer one. The post on the temporal dead zone covers that region, and the practical lesson is that a name is scoped from the start of its block, not from its declaration line.

switch has one block for all cases

A switch statement creates a single block around all its case clauses. Two let declarations with the same name in different cases are in the same scope, and that is a syntax error.

JavaScript
try {
  eval(`
    switch (1) {
      case 1:
        let message = "one";
        break;
      case 2:
        let message = "two";
        break;
    }
  `);
} catch (error) {
  console.log(error.name, error.message);
}

function label(kind) {
  switch (kind) {
    case "a": {
      const text = "alpha";
      return text;
    }
    case "b": {
      const text = "beta";
      return text;
    }
    default:
      return "unknown";
  }
}

console.log(label("a"), label("b"), label("z"));
Text
SyntaxError Identifier 'message' has already been declared
alpha beta unknown

The first part fails at parse time with a SyntaxError, reached here through eval so it can be caught. Wrapping each case body in braces gives each one its own scope, and the function works. The same pitfall appears when a let in one case is read in another: the variable exists, in its dead zone, and reading it throws. The post on switch statements covers the others.

catch parameters and try blocks

The catch clause has its own scope for the error name, and the try block is a block like any other, so declarations in it are not visible in catch or finally.

JavaScript
try {
  const attempt = "inside try";
  throw new Error("boom");
} catch (error) {
  console.log(typeof attempt);
  console.log(error.message);
}

console.log(typeof error);

let connection;
try {
  connection = "opened";
} finally {
  console.log(connection);
}
Text
undefined
boom
undefined
opened

A variable that finally must see, such as a handle to close, has to be declared before the try. That is the reason for the let connection; pattern. Declaring it inside the try block makes it invisible to the cleanup that needs it, which is a classic mistake in resource handling code.

Function declarations in blocks

A function declaration inside a block is block scoped in strict mode, which includes ES modules and classes. In sloppy scripts, browsers apply a compatibility rule that makes it visible in the enclosing function too, and the details differ between engines.

JavaScript
function outer() {
  if (true) {
    function helper() {
      return "inside";
    }
    console.log(helper());
  }
  return typeof helper;
}

console.log(outer());

const arrow = () => "ok";
console.log(arrow());
Text
inside
undefined
ok

In a module, helper is not visible after the block. The portable advice is to avoid function declarations inside blocks entirely: use a const with an arrow or function expression, which has unambiguous block scope everywhere.

Why function scope still matters

Even in code that never uses var, function scope shapes three things. Parameters and the function's own top-level let and const share one scope, so a body that redeclares a parameter name with let is an error. A function's arguments object exists at function scope. And closures capture the whole chain of scopes, so a function created inside a loop block keeps that block's bindings alive, which is the fact behind the per-iteration binding of let in loops, explained in the post on scope, hoisting and closures.

JavaScript
function redeclare(input) {
  try {
    eval("let input = 2;");
    return "allowed";
  } catch (error) {
    return error.message;
  }
}

console.log(redeclare(1));
Text
allowed

Here the eval runs in its own scope, so the redeclaration is allowed. A plain let input = 2; as the first statement of the function body would be rejected, because the parameter and the body share a scope.

A checklist for reading a scope bug

When a name is undefined or has an unexpected value, check four things in order. Is the declaration inside braces that closed before the use? Is a var hiding a leak that a let would have exposed? Is an inner declaration shadowing the one you meant? And is the use before the declaration in the same block, which puts it in the dead zone? Most scope bugs resolve at the first or second question.

Where block scope is not enough

If you need state to outlive a block, declare it in the enclosing scope and assign inside, as the connection example does. If you need isolation in an old script environment, a module is the modern answer, since each file has its own top-level scope, and a bare block or a function is the lightweight one. An immediately invoked function was the pre-module way to keep names private, and it is rarely needed now.

The rules are defined in the specification under scope analysis and declarations, and MDN's page on scope gives a short summary of the kinds.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.