JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 10: Scope and JavaScript BehaviorLesson 47 of 150About 35 minutes

Lesson 47: Lexical environments

01Opening question

A function is defined in one place and called from somewhere else. When it reads a variable, does it look where it was written or where it was called?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

show prints "outer": it looks up label where show was written, not where it was called.

const label = "outer";
function show() {
  console.log(label);
}
function run() {
  const label = "inside run";
  show();
}
run();

03Objective and prerequisites

Learning objective: Describe lexical scope and the scope chain, and predict variable lookup by reading where functions are defined, not where they are called.

You need: Lesson 46: Global, function and block scope

Skills practised: Lexical scope.

04Explanation

JavaScript uses lexical scope: what a name refers to is decided by where the code is written.

Every scope has a link to the scope around it. Looking up a name walks outward along these links: this path is the scope chain.

The lookup stops at the first scope that has the name. If no scope has it, you get a ReferenceError.

Inner functions can read outer variables, but outer code cannot read variables inside inner functions.

05Definitions

Lexical scope
Scope decided by where code is written in the source.
Scope chain
The sequence of outer scopes searched when a name is looked up.
Lexical environment
The engine's record of a scope's names plus a link to its outer environment.
Outer environment
The scope that surrounds the current one in the source code.

Open the full glossary

06Visual learning object

Scope chain explorer. Step through a lookup and watch the search move outward one environment at a time.

Loading the interactive object…

Open the full Scope chain explorer page with its guided experiment.

07Examples

ex-047-01Walking the chain Browser-executable JavaScript

Each lookup starts in the current scope and moves outward.

const company = "Acme";
function team() {
  const teamName = "Web";
  function member() {
    const person = "Ada";
    return `${person} / ${teamName} / ${company}`;
  }
  return member();
}
console.log(team());
Sample input
None
Expected output
Ada / Web / Acme
Common mistake
Thinking member needs teamName passed in as an argument.
Try this
Add a shadowing company inside team and predict the output.
Source
examples/ex-047-01-chain.js (repository pending publication)

ex-047-02Where it was written Browser-executable JavaScript

A function sees the variables around its definition.

const currency = "USD";
function format(n) {
  return `${n} ${currency}`;
}
function europeanCheckout() {
  const currency = "EUR";
  return format(20);
}
console.log(europeanCheckout());
Sample input
None
Expected output
20 USD
Common mistake
Expecting format to see the caller's currency.
Try this
Pass currency as a parameter so the caller controls it.
Source
examples/ex-047-02-defined-not-called.js (repository pending publication)

ex-047-03Outer cannot see inner Browser-executable JavaScript

Lookup only moves outward, never inward.

function outer() {
  function inner() {
    const secret = 42;
    return secret;
  }
  console.log(inner());
  console.log(typeof secret);
}
outer();
Sample input
None
Expected output
42 undefined
Common mistake
Trying to read a helper's variable from the caller instead of returning it.
Try this
Return the secret from outer as well.
Source
examples/ex-047-03-outer-cannot-see.js (repository pending publication)

ex-047-04A new environment per call Browser-executable JavaScript

Every call gets fresh local variables linked to the same outer scope.

let calls = 0;
function makeId(prefix) {
  calls += 1;
  const id = `${prefix}-${calls}`;
  return id;
}
console.log(makeId("user"), makeId("order"));
console.log(calls);
Sample input
None
Expected output
user-1 order-2 2
Common mistake
Assuming id keeps its value between calls.
Try this
Add a third call and predict all values.
Source
examples/ex-047-04-each-call.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Pass the value in

Use a parameter instead of relying on the caller's scope.

function greet() {
  return `Hello, ${name}`;
}
function welcome() {
  const name = "Grace";
  return greet();
}
console.log(welcome());

Trace the lookup

Predict which variable each name refers to.

const level = "global";
function a() {
  const level = "a";
  return b();
}
function b() {
  return level;
}
const result = "TODO";
console.log(result);

Configuration reader

Nest helper functions so they share outer variables safely.

// Write createReader(config)

09Prediction

Commit to an answer first, then run the real code to compare.

const x = "global";
function outer() {
  const x = "outer";
  return function () { return x; };
}
const fn = outer();
console.log(fn());

What is printed?

10Debugging investigation

The helper uses the wrong exchange rate

The conversion for euros should use the euro rate set in convertToEuro, but the result uses the default rate of 1.

const rate = 1;
function applyRate(amount) {
  return Math.round(amount * rate);
}
function convertToEuro(amount) {
  const rate = 0.92;
  return `${amount} -> ${applyRate(amount)}`;
}
const line = convertToEuro(100);
console.log(line);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reading code without running it

Code reviewers and editors resolve every name by reading the nesting of functions and blocks. Because JavaScript scope is lexical, "go to definition" in an editor always finds the same variable the program will use.

const taxRate = 0.2;
function invoice(amount) {
  const fee = 1;
  return amount * (1 + taxRate) + fee;
}
console.log(invoice(10));

12Knowledge check

1. What is printed?

const label = "outer";
function show() { return label; }
function run() { const label = "local"; return show(); }
console.log(run());
  • outer
  • local
  • undefined
  • An error

2. What decides which variable a name refers to?

  • Where the function is called
  • Where the code is written
  • The order functions run in
  • The variable's type

3. Which way does the scope chain search?

  • Inward to inner functions
  • Outward to enclosing scopes
  • Both ways
  • Only the global scope

4. Why does helper throw a ReferenceError?

function helper() { return rate * 2; }
function main() { const rate = 3; return helper(); }
main();
  • rate is declared inside main, which helper cannot see
  • helper is called too early
  • rate is const
  • Missing return

5. What is printed?

function tick(n) { const count = n; return count; }
console.log(tick(1), tick(2));
  • 1 2
  • 2 2
  • 1 1
  • An error

6. A helper needs the current user's name. Which is clearer?

  • Read a global currentUser
  • Accept the name as a parameter
  • Read it from the caller's local variable
  • Use var so it leaks

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Pass the value in: Prints Hello, Grace; greet works alone
  • Trace the lookup: Prints global; Calls a()
  • Configuration reader: Prints both; Unknown key throws; Readers are independent
  • ex-047-01: output matches the documented expected output
  • ex-047-02: output matches the documented expected output
  • ex-047-03: output matches the documented expected output
  • ex-047-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-047-lexical-environments/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Scope is lexical: decided by where code is written.
  • Lookup walks outward along the scope chain.
  • Each call creates a new environment linked to its definition's scope.
  • Pass values in as parameters rather than relying on the caller.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation lexical scope and the scope chain
Context: I am learning lexical scope and the scope chain in JavaScript.
Task: Explain lexical scope and the scope chain with nested functions, and how the engine looks up a name.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction lexical scope and the scope chain drill
Context: I have practised lexical scope and the scope chain.
Task: Give me six snippets where a function is defined in one place and called in another, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging lexical scope and the scope chain bug
Context: My function cannot see a variable that exists where I call it.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation lexical scope and the scope chain practice
Context: I finished the lexical scope and the scope chain exercises.
Task: Create three exercises that trace scope chain lookups.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review lexical scope and the scope chain review
Context: Here is my code that uses lexical scope and the scope chain.
Task: Review my code for functions that depend on hidden outer variables instead of parameters.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.