liveBook · Manning

Stack

As explained in Functional Programming in JavaScript

A last-in, first-out data structure in which elements are added and removed from one end called the top.

A stack stores elements so insertion and removal follow last-in, first-out order: the newest item is handled first. Operations happen at the top, like adding or removing dishes from a pile. JavaScript uses a context stack to manage function execution; the global context starts at the bottom, and each function call adds a frame. section 7.1

Function calls change the context stack in predictable ways:

  • Invoking a function pauses the current context and activates a new function frame. section 7.1
  • Returning from the function pops its frame, allowing the previous context to resume. section 7.1
  • Nested functions, currying, and recursion grow the stack with additional frames. section 7.1

Recursive calls

In `function increment(i) { console.log(i); increment(++i); }`, every recursive call adds another frame. Because no call returns, the stack continues growing until the runtime halts. section 7.1

Figure 7.2. When invoking any function, like logger in this case, the single-threaded JavaScript runtime pauses the current global context and activates the context for the new function to run. At this point, a link is created between the global context and the function context, traversable via the scopeChain. Once logger returns, its execution context is popped off the stack, and the global context resumes.

Visualizes the global context pausing, a function context becoming active, and the function frame being popped on return. section 7.1

How Functional Programming in JavaScript covers it

How deep it goes
Defines LIFO and traces frame creation, scope links, memory use, nesting, currying, and recursion.
Examples
Uses a dish pile, logger invocation, recursive increment, and longest-string recursion to illustrate stack behavior.
What it assumes
Assumes basic function calls and closures while teaching LIFO behavior and execution frames directly.
What you can do after
Evaluate how JavaScript calls pause, resume, allocate frames, and grow the execution stack.
How it connects
Links stacks to function execution, closures, scope chains, currying, and recursion.

Also explained in

Compare how 14 books explain stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.