DEV Community

Jennifer Tieu
Jennifer Tieu

Posted on

Self-Taught Developer Journal, Day 31: JavaScript Call Stack and Execution Context

Today I learned...

Execution Context

When a JavaScript executes a script or function, an execution context is created. An execution context has two phases: the creation phase and execution phase.

Every script always starts with creating the global execution context. Then, for every function call, a new function execution context is created and put on top of the call stack or execution stack.

let x = 10;

function timesTen(a){
  return a * 10;
}

let y = timesTen(x);

console.log(y); // 100
Enter fullscreen mode Exit fullscreen mode

Source: https://www.javascripttutorial.net/javascript-execution-context/

In the creation phase:

  • global execution context is created
  • global object is created
  • this object binding which references the global object is created
  • a memory heap is set up
  • variables and function declarations are stored in the memory heap with variables initial value set to undefined

Creation Phase Example Image

Next, in the execution phase:

  • the JavaScript Engine executes the code line by line.
  • values are assigned to variables and function calls are executed Execution Phase Example Image
  • for every function call, a new Function Execution Context is created
  • for the Function Execution Context creation stage, instead of creating the global object, it created the arguments object that contains a reference to all of the parameters passed into the function.
  • this value is set to the global object
  • "a" parameter is initialized with undefined Function Execution Context Creation Phase Example
  • Lastly, during the Function Execution Context execution phase, values are assigned and the function returns the result to the global execution context Function Execution Context Execution Phase Example

The Call Stack

The call stack works based on the LIFO principle, last-in-first-out. The functions are added to the call stack as the execution contexts are created.

Call Stack

The call stack has a fixed size (depending on the host environment). If the number of the execution contexts exceeds the size of the stack, a stack overflow will occur.

Resources

https://www.udemy.com/course/the-complete-javascript-course
https://www.javascripttutorial.net/javascript-execution-context/
https://www.javascripttutorial.net/javascript-call-stack/
https://amnsingh.medium.com/lexical-environment-the-hidden-part-to-understand-closures-71d60efac0e0

Top comments (0)