THE STACK

In 5ish Minutes

WHY YOU SHOULD CARE

  • It's fundamental to how JS works

  • It's helpful for debugging!

  • It comes up in interviews

WHAT IS THE CALL STACK?

A "todo list" of function invocations

TODO LIST

function: main

function: multiply

 function: something

Last In, First Out

TODO LIST

function: main

function: multiply

 function: something

Last In, First Out

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

Stack Youtube Video

By Colt Steele

Stack Youtube Video

  • 7,733