TIL a short explainer of the Execution Context
POSTED ON:
TAGS: javascript javascript-advanced mdn eli5
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).
- 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.
- 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:
- JS sees
oneHundred
needs a value. - JS then builds a new Execution Context for
timesTen()
, where it grabs all the parameters, prototypes, and inner code to get you data back. - If everything adds up, it'll then return that data. (
a * 10 = 100
) - It passes that data to
oneHundred
.oneHundred = 100
- 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: javascript