JavaScriptMedium
What is an execution context?
An execution context is the environment the engine creates to run a piece of code; it holds that code's variables, its scope chain and its this value, and a new one is created for the global code and for every function call.
Kinds of execution context
- Global: created once when a script starts.
- Function: created each time a function is called.
- Module: one per ES module.
- Eval: for code run through
eval(rare).
Two phases
- Creation: the engine sets up the environment. It registers declarations (functions fully,
varasundefined,let/const/classas uninitialised, which is the TDZ), links the outer environment for the scope chain, and decidesthis. - Execution: code runs line by line, assigning values and calling functions.
This two-phase setup is exactly what produces hoisting.
What each context contains
- A lexical environment with the variables and a reference to its outer environment (that link forms the scope chain and makes closures possible).
- The
thisbinding. - For functions, the arguments.
The call stack
Execution contexts are pushed onto the call stack when a function is called and popped when it returns. The context on top is the one currently running.
Why interviewers ask
It ties together hoisting, scope, closures and this. If you can explain creation vs execution and how contexts stack, those topics follow naturally.
Code example
js
1// Global execution context: creation phase already knows about these names2console.log(typeof double, typeof factor); // "function" "undefined"34var factor = 2;5function double(n) {6 // A new function execution context is created for every call:7 // - its own `n` and `result`8 // - an outer link to the global environment (so `factor` is visible)9 const result = n * factor;10 return result;11}1213console.log(double(5)); // 1014console.log(double(7)); // 14 - a fresh context, nothing left over from the last call1516// Closures keep a context's environment alive after the call returns17function makeAdder(base) {18 return (n) => base + n; // remembers `base` from makeAdder's context19}20const add10 = makeAdder(10);21console.log(add10(5)); // 152223// `this` is part of the context and is decided per call24const obj = {25 label: "obj",26 whoAmI() {27 return this?.label;28 },29};30const loose = obj.whoAmI;31console.log(obj.whoAmI(), loose.call({ label: "other" })); // obj other
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.