Separating the Call Stack From the Scope Chain

The quote service now has its wrappers and caches, and the next job is counting the museum guide’s words, section by section. Counting those words involves a function that calls itself for each section, and tracing it means keeping two questions apart. Where does a return send the program, and which variable does a name refer to?

In this lesson, you’ll draw two JavaScript structures that answer these questions and use that picture to explain closures and the temporal dead zone.

Follow Each Return on the Call Stack

The first structure answers “Who resumes after a return?” Each time a function is called, JavaScript makes a call frame for that call. A frame records where to resume in the caller, and it points to the environment holding the call’s local bindings, or associations between names and values. Frames pile up on the call stack. A call pushes a frame on top, and a return removes it so the frame below carries on.

Python works the same way, and its tracebacks list those frames. Here’s a module-level variable named region, a function that reads it, and a caller with a local of the same name:

Language: Python
region = "desk"

def read_region():
    return region

def caller():
    region = "caller"
    return read_region()

print(caller())  # desk

The JavaScript port has the same shape. A const declares a name that can’t be reassigned, and a function declaration works like def:

Language: JavaScript
const region = "desk";

function readRegion() {
  return region;
}

function caller() {
  const region = "caller";
  return readRegion();
}

console.log(caller());

JavaScript prints the module’s value, as Python does:

Language: Program Output
desk

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.