Study guides · Advanced

Execute JavaScript with environments and a call stack

Trace bindings, calls, returns, and closures separately, and explain why a function looks up names through its defining environment.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: separate lookup relationships from call order
  2. A nearer binding stops an outward lookup
  3. Create arguments and a return point for each call
  4. A closure is not a box of copied values
  5. Implementation: observe an environment after its call returns
  6. Failure: correctly assigning the wrong binding
  7. Exercise: change the defining and calling environments separately
  8. Ask Logeia about this articleCheck your understanding

Goal: separate lookup relationships from call order

When one function calls another, does the called function borrow the caller’s local variables? For ordinary JavaScript functions, name lookup follows the lexical environment associated with the function’s definition. The call stack instead records what is executing and where control should return. Drawing both relationships as the same arrow makes shadowing and closures difficult to explain. In this lesson, inspect the syntax tree, current environment, outer environments, call stack, and output separately. The prerequisites are expression trees and the distinction between function arguments and return values.

A binding such as let x = 1 associates a name with a value, but a useful implementation needs more than a dictionary of values. It also tracks whether a binding is initialized, whether assignment is allowed, and which environment owns it. A const binding forbids reassignment of that binding; it does not mean that every possible referenced object becomes immutable. The model does not implement general objects, yet preserving this distinction keeps the explanation accurate as we move from numeric values to functions that retain environments.

A nearer binding stops an outward lookup

With let x = 1 outside a block and let x = 7 inside it, there are two bindings. Assigning the inner x does not automatically update the outer one. Lookup begins in the current environment, proceeds outward when a name is absent, and stops at the first matching binding. Label the owner in the state display: block#2.x and global.x are more informative than a single row labeled x. That representation also makes backward stepping meaningful because it reveals exactly which binding changed.

Initialization is another boundary. If a block contains a lexical declaration, a reference before that declaration cannot simply fall back to an outer binding under standard JavaScript semantics. Check the teaching runtime’s declared rules and do not silently accept a construct it cannot model. An unbound name should not be given an invented zero or an accidental undefined value just to continue. A missing binding and a deliberately absent return value are different situations. Keeping them distinct makes both an error message and a state transition easier to verify.

Create arguments and a return point for each call

To evaluate add(3), evaluate the function value and arguments, then bind parameters in a new call environment. Its outer environment comes from the function’s retained defining environment. A stack frame records the executing function, its position, and the point at which its caller resumes. When return produces a value, end that call and deliver the value as the result of the call expression. Creating a new environment and choosing its outer link are separate operations, even if both occur during a call.

OperationCall stackEnvironment relationship
makeAdder(10)main → makeAdderBind base=10 in a new environment
add(3)main → caller → addThe outer environment was retained from makeAdder
returnmain → callerDeliver the numeric result to the caller

A closure is not a box of copied values

Consider makeAdder returning an inner function add that uses base. The call to makeAdder can finish while the environment needed by add remains available. Explaining a closure as a copy of every value at the instant of definition cannot explain a later update to an outer binding named rate. Think of a function value as carrying its body and access to the environment it needs. Changing a binding in that same environment can change a later lookup without changing the function’s body.

A caller with const rate = 100 does not become the outer lookup environment of add merely because it invokes add. That is the difference between lexical lookup and dynamic call order. Calling makeAdder twice also creates two base bindings, so the returned functions can retain different environments even when their source text is identical. Distinguish the same code, the same function value, and the same captured environment. These identities matter when the state view shows two function values that produce different results from identical arguments.

Implementation: observe an environment after its call returns

The standard JavaScript reference program below checks access to base and rate. Initially caller() returns 16, unaffected by its own local rate=100. After the outer rate changes to 4, add(3) becomes 22. The final printed values are 22 and 14. The function body has not changed. Explaining the result therefore requires recording which binding was read and when, rather than inspecting only the numeric argument to the latest call.

Use the supported named-function, binding, and return constructs in the interactive runtime to examine the same relationship. Recursion can increase call depth without increasing the size of the syntax tree. Reaching a finite call-depth limit is an incomplete run; the last visible rate or base value is not the result of the entire program. Parser size, evaluator operation count, and call depth are different resources. Keeping separate limits and diagnostics prevents the interface from confusing a resource boundary with an ordinary program answer.

javascript
let rate = 2;
function makeAdder(base) {
  function add(value) { return base + value * rate; }
  return add;
}
const add = makeAdder(10);
function caller() { const rate = 100; return add(3); }
console.assert(caller() === 16);
rate = 4;
console.assert(add(3) === 22);
console.log(caller(), add(1));

Failure: correctly assigning the wrong binding

A program intended to increment an outer counter may accidentally declare let counter = 0 in an inner block. Assignments can succeed while only that inner binding changes. This is not a failed assignment; it is a successful assignment to the wrong target. Decide which binding should own the state and how long it should live. Suitable repairs include removing an unnecessary shadowing declaration, passing an explicit argument, or returning a value for the caller to store. Choose a method that matches the intended data flow rather than renaming every identifier until one example happens to work.

Reassignment of const, missing arguments, and attempting to call a non-callable value are additional runtime boundaries after parsing. Follow the supported semantics rather than converting everything to zero or skipping a call and reporting success. Check that statements after an executed return do not continue within that invocation. Represent return and errors as control results, distinct from ordinary numeric values. That separation allows nested blocks and conditionals to compose without losing the fact that execution has already left the function.

Exercise: change the defining and calling environments separately

Repair the runtime task that reads an unintended inner binding. Decide which environment should provide the value, then make lookup reach that binding. Test one case with a changed outer value and another with a same-named variable added only to the caller. The first should affect a function that captures the outer binding; the second should not change lexical lookup. These related tests demonstrate a lookup rule more convincingly than one fixed expected output.

In your notes, record the retained environment for each function value, parameters created for each call, and the destination of each return value. Step backward and check that stack depth and visible bindings return to the earlier state. A call disappearing from the stack does not prove that every environment created by it has become unreachable. Finally, create two closures and change only one invocation path. Compare their retained state to detect unintended sharing. Being able to explain those identities is the bridge from small function examples to event handlers that retain state long after registration.

Try the interactive model

JavaScript syntax and execution

Loading demo checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 20

Choose a learning path