Thuta Learning
JavaScript
AdvancedProgrammingBeginner

Scope & Context

JavaScriptLesson 3125 min

What you'll walk away with

  • Tell global, module, function and block scope apart and predict where a variable is visible
  • Explain that var ignores blocks while let and const stay inside them
  • Know that the scope chain searches only outward, and that lexical scope is fixed by where code is written
  • Spot shadowing bugs and distinguish scope (variables) from context (this)

Explain it simply

Explain it simply

Think of a building. A notice pinned up in the lobby can be read by people from every room. Writing on a whiteboard inside one room, though, is visible only to people in that room, not to anyone in the lobby. Scope works like those rooms: it decides where in your code a variable can be read.

In JavaScript the rooms are nested inside each other. From an inner room you can see what is written in the outer rooms, but never the other way round. Every function and every { } block forms a new room.

Problem → Why → Solution

The problem: total was added to, yet it is still 0

You write a function to add up a shopping cart. Inside it, prices are clearly being added to total, but when the function finishes and you print total, you get 0. There is no error and no warning. The whole problem lives in one small word: the let in front of total.

cart.js
let total = 0;

function addItems(items) {
  let total = 0; // a NEW total that hides the outer one
  for (const item of items) {
    total += item.price;
  }
}

addItems([{ price: 5 }, { price: 7 }]);
console.log(total); // 0 — the outer total never changed

Why is it still 0?

The let total inside the function creates a new variable in the function's scope and hides the outer total; this is called shadowing. The loop updates only the inner total, which disappears when the function returns. The better fix is not to mutate the outer variable at all, but to return the result and write const total = addItems(items).

Core concept: four kinds of scope and the scope chain

Scope is the region of code where an identifier, such as a variable, function or class name, can be used. JavaScript has four main kinds. Global scope is the outermost and visible everywhere. Module scope is the top level of each ES module (a file using import/export); nothing in it is visible to other files unless exported. Function scope covers what is declared inside a function, and block scope covers the inside of if, for, while and plain { } braces.

The keyword decides which scope you get. let, const and class respect block scope and vanish when the closing brace is reached. var ignores blocks and lands in the nearest function (or the global) scope, which is why a var declared inside an if block can still be read after the block.

JavaScript uses lexical scope: what a function can see is decided by where its code is written, its nesting, not by where it is called from. When you use a name, the engine looks in the current scope first, then each enclosing scope outward until it reaches global. This path is the scope chain. If the name is found nowhere, you get a ReferenceError. The search only ever goes outward, never into inner scopes.

Declaring a variable in an inner scope with the same name as an outer one stops the search early and hides the outer variable; that is shadowing. It is legal, but as the problem section showed, it confuses readers. Global mutable variables that every file and function can change also couple distant parts of the code, and a value changed by one test leaks into the next. Parameters and module exports make those dependencies visible instead.

text
Looking up a name walks the scope chain outward
-----------------------------------------------
+-- global / module scope ------------------------------+
|  globalVar                                            |
|  +-- function outer() -------------------------------+ |
|  |  outerVar                                         | |
|  |  +-- function inner() ---------------------------+ | |
|  |  |  innerVar                                     | | |
|  |  |  uses outerVar:  inner -> outer (found)       | | |
|  |  +-----------------------------------------------+ | |
|  +---------------------------------------------------+ |
+-------------------------------------------------------+
Mental model: search from the inside out
  1. Look in the current block/function
  2. Not found: move one scope outward
  3. Reach global; still missing = error
  4. The first match wins (shadowing)

You can always look outward, but never peek inward.

General pattern

javascript
const shared = value;          // module/global scope

function name(param) {         // function scope: param, local
  const local = value;
  if (condition) {             // block scope
    const temp = value;        // gone after the closing brace
    var leaked = value;        // var escapes to function scope
  }
  return local;                // shared, param, local, leaked visible
}

Picture each scope as a set of braces. The innermost block sees everything outside it, but temp cannot be seen outside its block. var cuts through the block and ends up in the function scope.

Example: global, function, block and lexical scope

This example reads variables from each level of scope. Reading an out-of-scope name directly would throw a ReferenceError and stop the script, so those names are checked with typeof instead, which lets you run it and see every result. typeof returns "undefined" for an undeclared name instead of throwing.

scope.js
// Global (top-level) scope
let globalVar = "I'm global";

function demoScope() {
  // Function scope
  var functionVar = "I'm in function";

  if (true) {
    // Block scope
    let blockVar = "I'm in block";
    var notBlock = "I'm function scoped"; // var ignores the block

    console.log(globalVar);   // OK: outer scope
    console.log(functionVar); // OK: enclosing function
    console.log(blockVar);    // OK: same block
  }

  console.log(functionVar);   // OK
  console.log(notBlock);      // OK: var escaped the if-block
  console.log(typeof blockVar); // "undefined": blockVar is gone
}

demoScope();
console.log(globalVar);          // OK
console.log(typeof functionVar); // "undefined": function scope is private

// Lexical scope: inner functions see outer variables
function outer() {
  let outerVar = "outer";

  function inner() {
    let innerVar = "inner";
    console.log(`${outerVar} + ${innerVar}`);
  }

  inner();
}
outer();

Code breakdown

  1. Line 2let globalVar = "I'm global";

    Declared at the top level, so every function in the file can read it. In a classic script it is global; in an ES module it lives in module scope.

  2. Lines 10-11var notBlock = "I'm function scoped"; // var ignores the block

    blockVar (let) lives only inside the if block, but notBlock (var) ignores the block and belongs to demoScope's function scope.

  3. Line 19console.log(notBlock); // OK: var escaped the if-block

    The block has closed, yet notBlock is still readable. This var behaviour is the source of loop counters leaking out of their blocks.

  4. Line 20console.log(typeof blockVar); // "undefined": blockVar is gone

    blockVar is no longer visible outside the if block. Writing console.log(blockVar) directly would throw a ReferenceError; typeof reports "undefined" instead.

  5. Line 33console.log(`${outerVar} + ${innerVar}`);

    inner() has no outerVar, so the engine follows the scope chain up to outer() and finds it there. This works only because inner is written inside outer: lexical scope.

You should see
I'm global
I'm in function
I'm in block
I'm in function
I'm function scoped
undefined
I'm global
undefined
outer + inner

Scope and context (this) are different things

This lesson's title mentions "context", so it is worth separating the two. Scope decides where variable names are looked up and is fixed when the code is written. Context, the value of this, depends on how a function is called, for example which object it is called on, and is decided at run time. In the code below, the same function called through two objects gives a different this.label, while the label read from scope never changes.

scope-vs-this.js
const label = "module scope";

const box = {
  label: "box property",
  viaThis() {
    return this.label; // context: decided by the call
  },
  viaScope() {
    return label; // scope: decided by where the code is written
  },
};

const other = { label: "other object", viaThis: box.viaThis };

console.log(box.viaThis());   // box property
console.log(other.viaThis()); // other object
console.log(box.viaScope());  // module scope

In real projects

Where this shows up in real projects

Most JavaScript projects today are written as ES modules. Every file gets its own module scope, so two files can each have a helper with the same name without clashing, and only what you export is visible elsewhere. Before module systems, many script tags shared one global scope, and problems such as two libraries fighting over the name "$" were common.

Passing configuration into a function as a parameter, instead of reading a global, makes testing easier: each test supplies its own config without affecting the others. Values needed only for one loop iteration, declared with const inside the block, cannot leak out. ESLint's no-shadow rule warns about the kind of shadowing seen in the problem section, and TypeScript or ESLint also flag the use of undeclared variables.

Common mistakes

Common mistakes

1. Shadowing by accident

You meant to update the outer variable, but writing let or const again inside the function creates a new variable and the outer one never changes. Leave out the keyword if you only want assignment, or better, return the result.

2. Assigning to an undeclared variable

In a sloppy-mode script, writing count = 1; without let or const silently creates a new global variable. In ES modules and code with "use strict", it throws a ReferenceError instead. Always declare your variables.

3. var leaking out of a block

After for (var i = 0; i < 3; i++) {}, i is still around outside the loop with the value 3 and can collide with a later variable of the same name. With let, i exists only inside the loop.

Best practices

Best practices

  • Declare each variable in the smallest scope that needs it.
  • Pass values into functions as parameters and return results, rather than reading and writing globals.
  • Do not reuse names across nested scopes; turn on ESLint's no-shadow rule.

Mini challenge

Mini challenge: an order summary with no globals

Write summarize(), which takes a list of orders and a config object as parameters and returns a summary string. Use no global mutable state, and keep temporary values inside block scope.

  • Accept config ({ taxRate, currency }) as a parameter instead of reading a global
  • Declare each order's lineTotal with const inside the loop block
  • Round tax to 2 decimals and return a string like "items=2 subtotal=20.00 USD tax=2.00 USD"
  • Call it with two different configs and show with typeof that lineTotal never leaks out
summary.js
function summarize(orders, config) {
  // TODO: read taxRate and currency from config (not from a global)
  // TODO: let subtotal = 0
  // TODO: loop over orders; declare lineTotal with const inside the loop
  // TODO: round the tax to 2 decimals
  // TODO: return "items=N subtotal=X.XX CUR tax=Y.YY CUR"
}

// TODO: print summarize(...) for a USD config with taxRate 0.1
// TODO: print summarize(...) for a EUR config with taxRate 0.05
// TODO: print typeof lineTotal

Expected: One summary line per config, then undefined at the end: items=2 subtotal=20.00 USD tax=2.00 USD items=1 subtotal=30.00 EUR tax=1.50 EUR undefined

Show hint

You can destructure in the parameter list: function summarize(orders, { taxRate, currency }). Round with Math.round(x * 100) / 100 and display with toFixed(2).

Show solution
summary.js
function summarize(orders, { taxRate, currency }) {
  let subtotal = 0;
  for (const order of orders) {
    const lineTotal = order.qty * order.price; // lives for one iteration
    subtotal += lineTotal;
  }
  const tax = Math.round(subtotal * taxRate * 100) / 100;
  return (
    `items=${orders.length} subtotal=${subtotal.toFixed(2)} ${currency} ` +
    `tax=${tax.toFixed(2)} ${currency}`
  );
}

const usd = { taxRate: 0.1, currency: "USD" };
const eur = { taxRate: 0.05, currency: "EUR" };

console.log(summarize([{ qty: 2, price: 4.5 }, { qty: 1, price: 11 }], usd));
console.log(summarize([{ qty: 3, price: 10 }], eur));
console.log(typeof lineTotal);

Quick quiz 1 / 3

What does if (true) { var a = 1; let b = 2; } console.log(typeof a, typeof b); print?

Quick quiz 2 / 3

What is printed by let total = 0; function add(n) { let total = n; } add(5); console.log(total);?

Quick quiz 3 / 3

What does this print? const name = "global"; function printName() { console.log(name); } function run() { const name = "local"; printName(); } run();

What to remember

  • Scope decides where a variable is visible; the four kinds are global, module, function and block.
  • let, const and class respect block scope; var cuts through blocks into the function scope.
  • The scope chain searches only outward, and lexical scope is fixed by where code is written.
  • Avoid shadowing and global mutable state, and do not confuse scope (variables) with context (this).

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Scope & Context | Thuta Learning