The Call Stack and Execution Contexts

As we saw in the previous article, the call stack executes our code with execution contexts. 

What's an Execution Context?

  • It stores all the necessary information for executing our code. 
  • The creation stage of the execution phase creates execution contexts.
  • There's one global execution context and one execution context per function. 
  • The execution context is the default context created for the top-level code (outside of any functions).
  • Each function call creates one execution context.
  • Each execution context comprises a variable environment, scope chain and "this" keyword.

Variable Environment:

  • Declarations of let, const and var
  • Functions
  • arguments object (Not for arrow functions)

Scope Chain: 

  • We'll talk about this in the next article

"this" keyword:

  • Not present for arrow functions

Let's take a look at an example:

const age = 30;

const add10 = () => {
    let a = 10 + sum(8, 15);
    return a;
}

function sum(x, y) {
    return x + y;
}

const result = add10();
console.log(`Result of 8 + 15 + 10: ${result}`);
console.log(`The age is ${age}`);        

  • The above code snippet will produce a global execution context as follows : 

Global Execution Context:

age = 30
add10 = <function>
sum = <function>
result = unknown        

  • The "result" calls the "add10" function. Hence the "add10" will create an execution context as follows: 

add10 Execution Context: 

a = unknown        

  • The "add10" calls the "sum" function. Hence the "sum" will create an execution context as follows:

sum Execution Context:

arguments = [8, 15]        

The call stack looks as follows: 

Article content
The Call Stack

  • The call stack removes each execution context after it finishes its execution except for the global execution context.
  • We'll talk about scoping in the next article.

To view or add a comment, sign in

More articles by Gayatri Sarnobat

  • Who Am I? Understanding this in JavaScript Once and for All

    👉 Mastering this in JavaScript is less about memorization and more about context. JavaScript has an identity crisis —…

  • Scoping and The Scope Chain

    We looked at the call stack and the execution context in the previous article. We'll see the different types of scopes…

  • The JavaScript Engine and Runtime

    The JavaScript Runtime in the browser comprises a JavaScript engine such as v8 in Google Chrome, Web APIs provided by…

    1 Comment
  • Resolving Conflicting CSS Selectors

    Whenever we encounter an issue with which CSS selector gets applied to a specific element, the following information…

    1 Comment
  • Embrace Forgiveness!

    Too often, we punish ourselves for the mistakes we made in the past. The baggage of those things is so high that it…

Explore content categories