The Stack and the Heap

Objectives

  • Describe what the stack is

  • Describe a stack frame

  • Describe the heap

What is the Stack?

  • An ordered data structure

  • Keeps track of function invocations

  • Part of the JavaScript runtime (you don't access it directly)

How Your Code Changes the Stack

  • Whenever you invoke a function, the details of the invocation are saved to the top of the stack (pushed to the top)

  • Whenever a function returns, the information about the invocation is taken off the top of the stack (popped off of the top)

1  function multiply(x, y) {
2    return x * y;
3  }
4 
5  var res = multiply(3,5);

Stack Example

Stack:

1  function multiply(x, y) {
2    return x * y;
3  }
4 
5  var res = multiply(3,5);

Stack Example

5  function: main

Stack:

1  function multiply(x, y) {
2    return x * y;
3  }
4 
5  var res = multiply(3,5);

Stack Example

5  function: main

Stack:

2  function: multiply

1  function multiply(x, y) {
2    return x * y;
3  }
4  // res is 15
5  var res = multiply(3,5);

Stack Example

5  function: main

Stack:

1  function multiply(x, y) {
2    return x * y;
3  }
4
5  var res = multiply(3,5);

Stack Example

Stack (Empty):

1  function multiply(x, y) {
2    return x * y;
3  }
4 
5  var res = multiply(3,5);

Stack Frame:

From Stack Example

5  function: main

Stack:

2  function: multiply

Stack Frame

Stack Frame Contents

  • The function that was invoked

  • The parameters that were passed to the function

  • Current line number

5  function: main

2  function: multiply

Stack Definition

An ordered set of stack frames

Most recently invoked function is on the top of the stack

The bottom of the stack is the first function invoked

The stack is processed from top to bottom

Heap Definition

An area in memory where the your data is stored

 // The object is created in
 // the heap.  obj is a reference
 // to the object.
 var obj = {firstName: "Tim",
            lastName: "Garcia"};
 // New data is not created,
 // only a copy of the reference
 var referenceCopy = obj;

Stack

Example

The Stack and the Heap

By Elie Schoppik

The Stack and the Heap

  • 2,770