TExcelTAD
Home › JavaScript › JS Scope

JavaScript Scope

Scope determines where a variable can be seen and used. A variable declared in one part of the program may be invisible in another. Understanding scope prevents bugs like accidentally overwriting a variable, or wondering why something is "not defined".

JavaScript has these kinds of scope:

Scope Created by Variables declared with
Global the top level of a classic script var, let, const, functions
Module the top level of an ES module file var, let, const, functions
Function every function body var, let, const, parameters
Block any { … }: if, for, while, bare blocks let, const, class

Block scope

let and const only exist inside the nearest pair of braces:

js · try it yourself
const discount = 0.1;          // module-level: visible everywhere below

if (discount > 0) {
  const message = "Sale!";     // block-scoped
  console.log(message, discount);
}

try {
  console.log(message);
} catch (err) {
  console.log(err.message);
}
Sale! 0.1
message is not defined

Function scope

Variables declared inside a function — including its parameters — are local to that function. Each call gets a fresh set:

js · try it yourself
function makeGreeting(person) {
  const greeting = "Hello";
  return `${greeting}, ${person}`;
}

console.log(makeGreeting("Ana"));
console.log(typeof greeting, typeof person);   // not visible out here
Hello, Ana
undefined undefined

var ignores blocks but respects functions — another reason to prefer let/const:

js · try it yourself
function demo() {
  if (true) {
    var leaky = "I escape the block";
    let tidy = "I stay inside";
  }
  console.log(leaky);
  console.log(typeof tidy);
}
demo();
I escape the block
undefined

The scope chain

Scopes nest. When code uses a variable, JavaScript looks in the current scope first, then the enclosing scope, and so on outward until it reaches the global scope. Inner code can see outer variables, but not the other way round:

js · try it yourself
const app = "Shop";

function outer() {
  const user = "Mo";

  function inner() {
    const item = "lamp";
    console.log(app, user, item);   // sees all three
  }

  inner();
  console.log(typeof item);          // can't see inner's variable
}
outer();
Shop Mo lamp
undefined

This is called lexical scope: what a function can see is decided by where it's written in the source code, not where it's called from.

Shadowing

An inner variable with the same name as an outer one shadows it — inside the inner scope, the outer one is hidden:

js · try it yourself
let level = "global";
function show() {
  let level = "function";
  {
    let level = "block";
    console.log(level);
  }
  console.log(level);
}
show();
console.log(level);
block
function
global

Shadowing is legal but can confuse readers; use distinct names when you can.

Global variables

Variables at the top level of a classic <script> are global: every script on the page can read and change them. In ES modules (and these playgrounds), top-level variables are scoped to the module instead. Assigning to an undeclared variable in sloppy mode silently creates a global — in strict mode (which modules always use) it throws:

js · try it yourself
try {
  totalCount = 5;   // forgot let/const
} catch (err) {
  console.log(err.name + ": " + err.message);
}
ReferenceError: totalCount is not defined

Tip: Keep variables in the smallest scope that works. Fewer globals means fewer name collisions and code that's easier to reason about. Wrapping code in modules or functions is the standard way to avoid polluting the global scope.

Scope is also the foundation of closures — functions that remember variables from where they were created — covered in the Closures chapter.

Test yourself

Can an inner function read variables of its outer function?

  1. Yes
  2. No
  3. Only if declared with var
  4. Only global variables

Which declaration is NOT block-scoped?

  1. let
  2. const
  3. var
  4. class

What does lexical scope mean?

  1. Scope is decided by where the code is written
  2. Scope is decided at call time
  3. Variables are global by default
  4. Only strings have scope