Javascript Context Execution

Ignacio Ojanguren
2 min readNov 10, 2021

--

First article for Small Bites of Information

The execution context is the setup of the Javascript code in the Browser, so the browser is able to execute the piece of code you want to run.

There are two steps in the setup process: the Setup Phase, and the Execution Phase.

Let’s go over the phases with a code example:

// Calculates the square of a number
function square(number) {
return number * number
}
//Initializes a constant called 'Value', and the value is 2
const value = 2
// Calculate the square of 2
// and save it into a new constant called 'Result'
const result = square(value)

Setup Phase

Javascript is going to create the Global Execution Context, which sets up the following tasks:

  • Create the window object for the browser.
  • Creates this object, and assigns to it the window object.
  • Hoisting phase(future SBI about this topic), where it allocates space in memory for the variables and functions in the code.

Looking at the code the following variables and functions will be hoisted.

  • square will be initialized as an empty function.
  • value will be initialized with undefined value.
  • result will be initialized with undefined value.

After the setup phase is done Javascript will jump to the next step, the Execution Phase.

After the setup phase is done Javascript will jump to the next step, the Execution Phase.

Execution

During this phase Javascript is going to execute line by line.

Let’s simulate we are the browser and we are going to execute line by line.

function square(number) {
return number * number
}

We find a function declaration. For every function Javascript is going to create a new execution context or Function Execution Context.

This Function Execution Context works very similar to the Global Execution Context.

  • For the setup phase it does the same thing as in the Global Execution Context. However, instead of creating the window object, it creates the argument object. Javascript will allocate space in memory for the variable number.
const value = 2

The value in the memory allocation for value is going to be replaced from undefined to the new value 2.

const result = square(value)

The value in the argument in the Function Execution Context is going to change from undefined to 2. The function will return the square of that value 4, and the value will be stored in the allocated memory result.

I used this article to refresh how the Execution Context works https://www.javascripttutorial.net/javascript-execution-context/

--

--

Ignacio Ojanguren

Over 3 years of experience as a Software Engineer at Privy, recently acquired by Attentive Mobile. I am Learning, and I hope I can share what I learn with you.