【JavaScript】Execution Context and CallStack

The actual contents comes from The Complete JavaScript Course 2021.

If you have interests, you can check The Complete JavaScript Course by Jonas Schmedtmann.

After Compiling, Execution in Detail

  1. Global Execution Context is created for the top-level code.
  2. Top-Level code be executed.
  3. After Top-Level code is finished, functions start to execute.

What is top-level Code?

It’s code that is not inside any function, in the beginning only the code that is outside of functions will be executed.

What is Execution Context?

JavaScript code always runs inside an execution context.

Only One Global Execution Context

One Execution Context — One Function

What’s inside Execution Context?

  1. Variable Environment

All our variables and function declarations are stored, and there’s also a special arguments object.

What’s inside the Arguments Object?

Argument object contains all the arguments that were passed into the function that the current execution context belongs to.

2. Scope

Lexical scope consists of references to variables that are located outside of the current function.

3. this keyword

Creation Phase

The content of the execution context, variable environment, scope, and this keyword is generated in so-called Creation Phase.

Which happens right before execution.

What is Call Stack?

The execution context that is on top of the stack, is the one that is currently running.

When it finishes running, it will be removed from the stack and execution will go back to the previous execution context.

How Call Stack Work?

1. Top-Level code start execution, and Global Execution Context created for the Top-Level code.

2. Global Execution Context be put in the Call Stack.

3. When a function is called, it gets its own Execution Context, and put in the call stack, on top of the current context, now it’s the new current Execution Context.

4. The function below the current Execution Context will be paused.

5. When a function return, meaning it will finish its execution, so the function’s Execution Context, will be popped off the stack.

6. The previous Execution Context, will be back to being the current Execution Context.

7. If the program only left with Global Execution Context, it will stay in this state until the app is eventually finished, then Global Execution Context popped off the stack.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store