Today I Learned - Rocky Kev

TIL a short explainer of the Execution Context

POSTED ON:

TAGS:

What is the Execution Context?

We're going into deep Javascript territory here:

So Javascript has 2 steps when it goes from code into the engine (in the browser).

  1. The creation Step:
    This step picks out all the variables and functions, and makes a note that they exist.

This DOESN'T assign anything!

If you said

const name = "Anakin",

then it makes a note that a name variable exists.

  1. The execution Step:

This is where is assigns values.
That name variable now has a Anakin attached.

const name = "Anakin",

But what about functions?

Well, this is were the Execution Context comes in.

It is an abstract concept that represents the environment in which JavaScript runs. What happens inside the execution context is two things basically. The first is parsing the code line by line and the second is storing the variables and functions into the memory.

As Javascript runs top to bottom, it starts building code together.

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

// ... many lines later

const oneHundred = timesTen(10);

console.log(`There are ${oneHundred} apples`);

So here, it's creating a new Execution Context for timesTen. It pops it on the Call Stack as a task to do, does the task, then gets rid of the Execution Context.

So:

  1. JS sees oneHundred needs a value.
  2. JS then builds a new Execution Context for timesTen(), where it grabs all the parameters, prototypes, and inner code to get you data back.
  3. If everything adds up, it'll then return that data. (a * 10 = 100)
  4. It passes that data to oneHundred. oneHundred = 100
  5. It now outputs that number in console.log.

Here's a visual on it - from the blog post #3.

REFERENCES:
#1 - The ECMA Script Definition

#2 - JS tutorial

#3 - Understanding JavaScript Execution Context and How It Relates to Scope and the this Context


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.