Execution contexts & jobs in the spec
Read how ECMAScript tracks running and suspended code with execution contexts, environment records, realms, generators, and host-scheduled jobs.
- 01Find the running contextSay which context is running. Name the notes it keeps: its realm, the script or module it came from, and its records of names.
- 02Follow a pauseExplain how a generator or an async function can pause, and later carry on with the same saved values.
- 03Find the host's partTell the spec's jobs apart from the event loop of a browser or Node, which decides when jobs run.
A context keeps track of running code
When JavaScript runs a function, it must remember two things. Which code is running right now? And where should it look for names like user? The specification is the official rule book for JavaScript. It keeps those notes in an execution context. In this lesson we'll often just say "context".
function greet(user) {
return "Hi, " + user;
}
console.log(greet("Asha"));Line 1 makes a function called greet. Line 2 joins "Hi, " and the name in user. Line 4 calls greet with "Asha" and prints Hi, Asha. While greet runs, it has its own context. When it finishes, that context is no longer needed.
An execution context is a set of notes that the specification uses to describe running code. It is not a JavaScript value. Your code can't print it, save it, or read it as a property. A real engine may store these notes in any way it likes. The notes also say where to carry on if the code pauses and starts again later.
This lesson follows Environment Records. That lesson showed where names are kept. This lesson asks three new questions:
- Which context is running right now?
- What does a context remember while it waits?
- How does work that runs later get started?
If calls are new to you, start with the call stack lesson first.
The stack of contexts
JavaScript keeps its contexts in a pile, one on top of another. The spec calls this pile the execution context stack. The context on top is the running execution context: the one whose code runs now. When code calls a function, a new context goes on top and starts running. The caller's context stays underneath and waits.
function getPrice() {
return 3;
}
console.log(getPrice());Line 1 makes a function called getPrice. Line 2 gives back 3. Line 4 calls it and prints 3. While getPrice runs, its context is on top. When it returns, its context comes off the pile. Then the script finishes line 4.
The spec says the same thing in two sentences. Here they are, quoted word for word:
"The running execution context is always the top element of this stack."
"The newly created execution context is pushed onto the stack and becomes the running execution context."In plain words, line by line:
- The context on top of the pile is always the one that runs.
- A new context goes on top of the pile, so it becomes the one that runs.
Both lines come from ECMA-262, Execution Contexts. Your code can't see the pile. You only see its effect: the caller waits until the call returns.
function addTax(price) {
return price + 2;
}
function total() {
return addTax(3);
}
console.log(total());Now one function calls another. Line 7 calls total. Line 5, inside total, calls addTax with 3. Line 2 adds 2 and gives back 5. Line 7 prints 5. The picture shows the pile while line 2 runs.
addTax, runs; the two below it wait.The replay below runs the real total and addTax functions and shows each step. It is a recording made for this lesson, not a view inside a real engine.
A recording of the real example functions, made for this lesson. It is not an engine debugger.
script
function addTax(price) { return price + 2;}function total() { return addTax(3);}You are writing on one notebook page. You stop and turn to a new page for a quick sum. When the sum is done, you turn back and carry on where you stopped.
- In real life: You write on one open page
- In JavaScript: One context is running
- In real life: You turn to a new page
- In JavaScript: A call puts a new context on top
- In real life: You turn back to the old page
- In JavaScript: The caller carries on
The last context to go on the pile is the first to come off. Here, addTax finishes before total does. Later in this lesson you'll see a generator. A generator can pause, leave the pile, and come back later. For more pictures of calls, see the call stack lesson.
What a context remembers
A context is more than a place in the pile. It holds a few notes about the code it runs. The spec calls each note a component. Every context has these four:
- Code evaluation state: how far the code has got, so it can pause and carry on later.
- Function: the function that is running, if there is one.
- Realm: the set of built-in objects and globals this code uses. You'll see realms later in this lesson.
- ScriptOrModule: the script file or module file the code came from.
function order(user) {
return user + " ordered tea";
}
console.log(order("Asha"));Line 1 makes a function called order. Line 2 joins the name in user and " ordered tea". Line 4 calls order and prints Asha ordered tea. While order runs, its context's Function note says order. The script around it is not inside any function, so the script's Function note is null, which means "nothing".
Here is how the spec describes the four notes. These lines are shortened from its table:
"code evaluation state" — state needed to perform, suspend, and resume evaluation
"Function" — the function object, or null for a Script or Module
"Realm" — the Realm Record used to access ECMAScript resources
"ScriptOrModule" — the originating Script Record or Module Record (or null)In plain words, line by line:
- Code evaluation state: everything needed to run the code, pause it, and carry on later.
- Function: the function being run, or
nullfor a script or module that is not inside a function. - Realm: which set of built-in objects and globals the code uses.
- ScriptOrModule: which script or module the code came from, or
nullif there is none.
Some contexts have extra notes, which you'll meet in the next section. The table lists all eight. Read each row as: "this note answers this question, and it does not mean this other thing."
| Note | What question it answers | What it does not mean |
|---|---|---|
| Code evaluation state | How far has the code got, so it can pause and carry on later? | It is a note in the spec, not a property your code can read. |
| Function | Which function is running? It is null for a script or module that is not inside a function. | It is not a list of every function waiting on the stack. |
| Realm | Which set of built-in objects and globals does the code use? | It is not the file name, and it doesn't load modules. |
| ScriptOrModule | Which script or module did the code come from? It is null if there is none. | It is not the stack of contexts, and it is not an import address like "./cart.js". |
| LexicalEnvironment | Which record of names does lookup start in? | It is not always the same record as VariableEnvironment. |
| VariableEnvironment | Which record holds the names made with var? | It doesn't move into each block the code enters. |
| PrivateEnvironment | Which private names, like #item, can the code use? It is null when no class is around the code. | It doesn't hold the value of a private field on an object. |
| Generator | Which generator is this context running? | Only a generator's context has this note. |
The table follows the spec's Execution Contexts section. None of these notes is a property you can read from JavaScript. An engine is free to store them however it likes.
Where a context looks up names
In the last lesson you met Environment Records. An Environment Record, or just "record", is a list of names and their values for one scope, such as one function or one block. A context running JavaScript code has two notes that point at records:
- LexicalEnvironment: the record where name lookup starts.
- VariableEnvironment: the record where names made with
varare kept.
Often both notes point at the same record. Inside a block, they can point at different records.
function receipt() {
var price = 3;
if (true) {
let note = "tea";
console.log(note, price);
}
}
receipt();Line 1 makes a function called receipt. Line 2 puts 3 in price, using var. Line 3 starts a block, the code between the curly brackets of the if. Line 4 makes note with let, so note only exists inside the block. Line 5 finds both names and prints tea 3. Line 8 calls the function.
Inside the block, the LexicalEnvironment note points at a new record for the block. The VariableEnvironment note still points at the function's record, where price is.
note. var price lives in the function's record, and the outer link leads there.The spec lists these notes, plus two more, for contexts that run JavaScript code. These lines are shortened from its table:
"LexicalEnvironment" — resolves identifier references
"VariableEnvironment" — holds bindings made by VariableStatements
"PrivateEnvironment" — holds Private Names in the nearest containing class
"Generator" — the Generator this context evaluates, for generator contextsIn plain words, line by line:
- LexicalEnvironment: the record to search when the code reads a name.
- VariableEnvironment: the record that holds names made with
var. - PrivateEnvironment: the record of private names, like
#item, from the nearest class around the code. It isnullwhen no class is around the code. - Generator: the generator this context runs. Only generator contexts have this note.
You can read the full table in the spec's Execution Contexts section.
var price = 3;
{
let price = 5;
console.log(price);
}
console.log(price);Line 1 puts 3 in an outer price. Line 3 makes a different price, with the value 5, inside the block. Line 4 prints 5. Line 6 is outside the block, so it prints 3. The inner price hides the outer one. It doesn't change it.
When a record doesn't have a name, JavaScript follows the record's outer link to the next record out. The spec calls this link [[OuterEnv]]. Entering a block adds a new record. It does not add a new context to the pile.
The table compares the three ways a context finds a name. Read each row as: "this part does this job, and it is different from this other thing."
| Part | What it does | How it is different |
|---|---|---|
| LexicalEnvironment | Finds note when the code inside the block reads it. | It can point at a new record when the code enters a block. |
| VariableEnvironment | Keeps var price in the function's record. | It stays on the function's record, even inside the block. |
[[OuterEnv]], the outer link | Leads to the next record out when the current record doesn't have a name. | It joins records of names. It does not join calls on the stack. |
Old words: the variable object
Old versions of the spec, such as ES3 from 1999, used a different word. They said each context had a variable object: one object that held all of its variables. You will still see this word in old articles and books. Today's spec doesn't use it. It uses Environment Records with outer links instead.
var price = 3;
let note = "tea";
console.log(price, note);Line 1 makes price with var. Line 2 makes note with let. Line 3 reads both and prints 3 tea. Your code only ever reads names like these. It can't reach a variable object or an Environment Record.
So why does the change matter? An old picture may show every scope as one plain object. That picture misses some cases. Today's spec has five kinds of records: declarative, object, global, function, and module. Each kind handles its own cases. You can read them in the spec's Environment Records section.
When you read today's spec, ask two questions. Which record holds the name? Where does its outer link, [[OuterEnv]], point? The Environment Records lesson covers those records. This lesson covers the context that points at them while it runs.
Only the words changed. Old browsers didn't have to keep every variable in one object, and new engines don't have to make a record for every block. The spec only says what your code must see. An engine can do the work in a faster way, as long as the result is the same.
Realms and where code came from
Two of a context's notes answer two different questions. Which built-in objects does the code use? And which file did the code come from?
- The Realm note answers the first question. A realm is one full set of built-in objects, such as
ArrayandObject, plus one global object and its global names. The spec calls the built-in objects intrinsics. - The ScriptOrModule note answers the second question. It points at the spec's record for the script or module the code came from.
const cart = [];
console.log(Object.getPrototypeOf(cart) === Array.prototype);Line 1 makes an empty array called cart. Line 2 asks for the array's prototype, the object it gets its methods from. It checks whether that is this realm's Array.prototype, and prints true. This code only has one realm. A page with an <iframe> has a second realm, with its own Array.prototype. An array made inside the iframe, checked against the main page's Array.prototype, gives false.
function receipt() {
return "tea";
}
console.log(receipt());Line 1 makes a function called receipt. Line 2 gives back tea. Line 4 prints tea. While receipt runs, its ScriptOrModule note still points at the script it came from. The note is not a file name string like "receipt.js". It doesn't schedule any work either.
You can read more in the spec's Realms section and its table of context notes. For an example with two realms, see Realms and globals.
One more word. Each realm belongs to an agent. An agent owns one pile of contexts and runs one context at a time. It is a spec idea too. It does not have to be its own thread in the computer.
Jobs: work that runs later
Some code doesn't run right away. It waits until the current code has finished. The spec calls a piece of waiting work a job. A job starts only when no other JavaScript code is running in its agent.
Who decides when a job runs? The host does. The host is the program that runs JavaScript, such as a browser or Node. The spec sets a few rules for the host. It does not describe one event loop that every host must use.
console.log("start");
Promise.resolve("tea").then((order) => console.log(order));
console.log("end");Line 1 prints start. Line 2 makes a promise that already holds "tea". Its .then() hands over a function, called a handler, to run with the value. The handler doesn't run now. It becomes a job for later. Line 3 prints end. The script is now finished, so the job runs and prints tea. The order is start, end, tea.
start and end first. The then handler runs later, as a job, and prints tea.The spec says this in two sentences. Here they are, quoted word for word:
"A Job is an Abstract Closure with no parameters that initiates an ECMAScript computation when no other ECMAScript computation is currently in progress."
"Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them."In plain words, line by line:
- A job is a small piece of work with no inputs. It starts JavaScript code, but only when no other JavaScript code is running.
- Promise jobs run in the same order they were added to the waiting line.
Both lines come from the spec's Jobs and Host Operations section. The spec names two ways to hand a job to the host:
- HostEnqueuePromiseJob adds a promise job. Promise jobs must keep their order.
- HostEnqueueGenericJob adds any other job. The host may run it whenever it likes.
Promise.resolve().then(() => console.log("first"));
Promise.resolve().then(() => console.log("second"));
console.log("now");Line 1 adds a handler that prints first. Line 2 adds a handler that prints second. Line 3 prints now straight away. Then the two handlers run in the order they were added: first, then second. Your code can't look inside the host's waiting line. You only see the order of the output.
The table keeps four words apart that are easy to mix up. Read each row as: "this word means this, and here is one way to tell it apart."
| Word | What it means | How to tell it apart |
|---|---|---|
| Execution context | The spec's notes about code that is running or paused. | It keeps track of one piece of running code. It is not a waiting line of work. |
| Execution context stack | The pile of contexts in one agent. | The context on top is the one that runs. |
| Job | A small piece of work, with no inputs, that starts JavaScript code later. | The host starts it only when no other JavaScript code is running. |
| HostEnqueuePromiseJob | The way the spec hands a promise job to the host. | Promise jobs run in the order they were handed over. |
| HostEnqueueGenericJob | The way the spec hands any other job to the host. | It has no order rule. It doesn't describe a browser's list of tasks. |
console.log("script");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));Line 1 prints script. Line 2 asks the host for a timer with setTimeout. Line 3 adds a promise handler. The output is script, promise, timer. A timer is not a promise job. The browser has its own rules for timers, and the JavaScript spec doesn't set them.
To learn those host rules, see the event loop and microtasks lessons. This lesson only needs two facts from the spec. A promise handler is later work. And two jobs in the same agent never run at the same time.
Pausing and carrying on
So far, every call ran from start to finish in one go. A generator is different: it can pause in the middle. You make one with function*, a function with a star. Calling it doesn't run its body. It gives back a generator object instead. Each time you call the object's next() method, the body runs until the next yield. At yield, the generator pauses and hands a value back to the caller.
function* orders() {
yield "tea";
return "done";
}
const order = orders();
console.log(order.next().value);
console.log(order.next().value);Line 1 makes a generator function called orders. Line 5 calls it. The body doesn't run yet; order just holds the generator object. Line 6 calls next(). The body runs to the yield on line 2, pauses, and hands back tea, which line 6 prints. Line 7 calls next() again. The body carries on right after the yield, reaches return "done" on line 3, and line 7 prints done.
While the generator is paused, its context leaves the pile. Its notes are kept safe, so it can carry on later from the same place.
The next box shows spec steps. Spec steps read like a recipe, one step per line. A ? means "stop and throw if this fails". These three steps are quoted from different parts of the spec:
"Set gen.[[GeneratorState]] to SUSPENDED-YIELD."
"Return ? RunCallerContext(iteratorResult)."
"Return ? RunSuspendedContext(genContext, NormalCompletion(value))."In plain words, line by line:
- At
yield: mark the generator as "paused at a yield". - Then go back to the caller's context and hand it the result, such as
tea. - On the next
next()call: run the saved generator context again, from where it paused.
The full steps are in GeneratorYield, GeneratorResume, and RunSuspendedContext. The context's Generator note links it to the generator object. Its code evaluation state says where to carry on.
Here is a generator that keeps a number, count, between calls. The picture shows count after each next().
count while it is paused. The second next() carries on after the first yield, so count goes from 1 to 2.function* countOrders() { let count = 1; yield count; count += 1; yield count;}const orders = countOrders();console.log(orders.next().value);console.log(orders.next().value);not startedThe body has not run yet.
noneThe third call finishes the generator. It prints nothing more.
The generator object exists, but its body has not run yet. Press Call next().
A recording of two real next() calls, made for this lesson. It is not an engine debugger.
script
function* countOrders() { let count = 1; yield count; count += 1; yield count;}console.log(orders.next().value);console.log(orders.next().value);In the playground, press Call next() once to see 1. Press it again to see 2. Press it a third time to finish the generator. The panel is a model made for this lesson, not a view inside a real engine. A test runs the same three calls on the real code. Reset goes back to the start, before the first next() call.
An async function can pause too. It pauses at await, which waits for a promise.
async function receipt() {
console.log("before");
await Promise.resolve();
console.log("after");
}
receipt();
console.log("outside");Line 6 calls receipt. Line 2 prints before. Line 3 waits for a promise. The promise already has its value, but the function still pauses here. Its context leaves the pile, and the script carries on: line 7 prints outside. Later, a promise job wakes the function up. It carries on after the await, so line 4 prints after. The output is before, outside, after. The function did not start again from line 1. It carried on from where it paused.
The spec's Await steps save the async function's context. Then they use a promise handler to run it again later. For more on async and await, see the async/await lesson. A pile that only grows and shrinks can't explain this. You also need the idea that a context can pause, leave the pile, and come back.
Using this in a real app
Picture a checkout page. It works out a total. After a promise, it updates a message. Later, the shopper clicks a button. These three things don't happen in one long call:
- Working out the total is a normal function call. It uses the pile of contexts right away.
- The message update runs later, as a promise job.
- The click comes from the browser, the host. The browser decides when click and timer code runs.
function showTotal(price) {
return price + 2;
}
console.log(showTotal(3));Line 1 makes a function called showTotal. Line 2 adds a fee of 2 to the price. Line 4 calls it with 3 and prints 5. This is a normal call. The function's context goes on top of the pile, runs, and comes off. Then the script carries on.
const order = { item: "tea" };
console.log(order.item);Line 1 keeps an order object in order. Line 2 prints tea. This code doesn't make a new agent. Remember, an agent owns one pile of contexts and runs one context at a time. The spec's Agents section lets separate agents, such as a page and a web worker, run side by side. It doesn't say each agent needs its own thread in the computer.
On a real site, this model helps you answer three questions:
- Which scope does this name belong to?
- Where does this function pause?
- Which step is up to the host, such as a click or a timer?
When the order of your output surprises you, add a console.log before and after each pause or handler. Don't assume a handler runs inside the call that set it up. The microtasks lesson covers the browser's rules. Node's event loop covers Node's rules.
- Where the running code starts looking for
note - The function that is running right now
- The script or module the code came from
- Where a promise handler waits to run later
- When a job with no order rule runs
- Which
Array.prototypethe code uses
Put each clue in the group it belongs to. Then read the explanation.
Common mix-ups
The pile of contexts, a job, a realm, and a record each answer a different question. If you keep them apart, spec steps are much easier to read. Start with one small call.
function getPrice() {
return 3;
}
console.log(getPrice());Line 1 makes a function called getPrice. Line 2 gives back 3. Line 4 calls it and prints 3 right away. No promise handler and no job are needed for a normal call like this.
- "Every context is one block of memory in the engine." A context is a set of notes in the spec. An engine can store it any way it likes, and a context can pause.
- "A paused generator is still running." Its context leaves the pile while it waits, and comes back on the next
next(). - "A realm is a waiting line of jobs." A realm is a set of built-in objects and a global object. It doesn't hold jobs.
- "The JavaScript spec defines the browser's event loop." The spec only defines jobs and the ways to hand them to the host. The browser or Node decides the rest.
- "VariableEnvironment is one object with every variable in it." Both LexicalEnvironment and VariableEnvironment point at records, and a block can have its own record.
The table puts four of these ideas side by side. Read each row as: "this is what it is, and this is what it is not."
| Idea | What it is | What it is not |
|---|---|---|
| A context | The spec's notes about running code. It can pause. | A JavaScript object you can see, or exactly one block of engine memory. |
| A realm | A set of built-in objects and a global object for code to use. | The script file, a waiting line of jobs, or the same thing as an agent. |
| A promise job | Work handed to the host, with a rule about order. | A timer, or one event loop that every host must use. |
| A paused generator | It keeps its saved values until it carries on or finishes. | A call that stays running on the stack the whole time. |
Two explanations may seem to disagree. Check whether one is about a normal call that runs to the end, and the other is about code that pauses. The simple pile is right for normal calls. Generators and await add one more idea: a context can pause, leave the pile, and come back later.
Practice exercises
Start with a normal call. Then follow two names called price, a promise handler, and a paused generator. Type your answer in the box to check it. Then compare the worked solution with the code you ran.
Read the last line first: it calls total. Follow the call inside it, then write the number that gets printed. Which function's context is running while the adding happens?
function addTax(price) {
return price + 2;
}
function total() {
return addTax(3);
}
console.log(total());console.log(3 + 2); // 5addTax runs and finishes before total can give back its answer. The last line prints 5.
The block makes a new price. Write the two printed numbers in order. Inside the block, which record does JavaScript search first?
var price = 3;
{
let price = 5;
console.log(price);
}
console.log(price);console.log(5);
console.log(3);The block prints its own price, 5. Then the code outside the block prints the outer price, 3.
A customer orders tea, and a promise handler prints the item. Write the three printed lines in order. The promise already has its value, but the handler still waits.
console.log("start");
Promise.resolve("tea").then((order) => console.log(order));
console.log("end");console.log("start");
console.log("end");
console.log("tea");The output is start, end, tea. The handler runs later as a promise job. It is not a timer.
The first next() hands back tea and pauses the generator. On the second next(), where does the code carry on? Describe the place in a few words.
function* orders() {
yield "tea";
return "done";
}
const order = orders();
console.log(order.next().value);
console.log(order.next().value);function* orders() {
yield "tea";
return "done";
}
const order = orders();
order.next(); // hands back tea, then pauses
console.log(order.next().value); // doneThe saved generator context carries on after the yield. It doesn't start over.
Your checkout page shows a price plus a small fee. While the adding runs, which function's context is running? Name it before you change any app code.
function showTotal(price) {
return price + 2;
}
console.log(showTotal(3));function showTotal(price) {
return price + 2;
}
console.log(showTotal(3)); // 5showTotal is running while price + 2 is worked out. The script carries on after it gives back 5.
Think of this as a receipt update after checkout. Predict the three printed lines. Then say which line runs after the function pauses at await.
async function receipt() {
console.log("before");
await Promise.resolve();
console.log("after");
}
receipt();
console.log("outside");console.log("before");
console.log("outside");
console.log("after");The async function pauses at await. The script prints outside. Then a promise job wakes the function up, and it prints after.
Check your understanding
Follow the normal calls first, then think about later work. For each question, ask what it is about: the running context, a record of names, a realm, or a job.
Question 1 of 7When total calls addTax, which context runs?
Choose an answer to see the explanation.
Question 2 of 7What does this addTax call print?
Read the code, then predictfunction addTax(price) { return price + 2; } console.log(addTax(3));Choose an answer to see the explanation.
Question 3 of 7Inside a block, which note says where to start looking for the name note?
Choose an answer to see the explanation.
Question 4 of 7What does this code with two price names print?
Read the code, then predictvar price = 3; { let price = 5; console.log(price); } console.log(price);Choose an answer to see the explanation.
Question 5 of 7Who decides the details of the browser's or Node's event loop?
Choose an answer to see the explanation.
Question 6 of 7What does this promise code print?
Read the code, then predictconsole.log("start"); Promise.resolve("tea").then((item) => console.log(item)); console.log("end");Choose an answer to see the explanation.
Question 7 of 7What happens when a generator reaches yield?
Choose an answer to see the explanation.
If a code question surprises you, run the code. Then explain each printed line: which context was running, and was it a job? The quiz is about the spec's words, not about engine speed or how one engine is built.
Key takeaways
The spec keeps three questions apart. What is running now? What is saved for later? And who decides when later work runs? Normal calls and code that pauses use the same words, but they don't behave the same way.
- Contexts sit in a pile. The context on top is the one that runs.
- A context is a set of notes in the spec, not a value your code can see. Its notes say where to carry on after a pause.
- LexicalEnvironment is where name lookup starts. VariableEnvironment holds
varnames. PrivateEnvironment holds a class's private names. - Function, Realm, ScriptOrModule, and (for generators) Generator each answer a different question about the running code.
- Promise handlers run later as jobs, through HostEnqueuePromiseJob. The host runs the event loop and follows the spec's rules.
- A generator pauses at
yieldand carries on at the nextnext(). An async function pauses atawait, and a promise job wakes it up.
Remember the one-liner.
A context keeps track of running code; a job is work for later; the host decides when the job runs.
Coming next: Function calls: [[Call]] & [[Construct]]. You'll see how calling a function makes and sets up the context this lesson followed. To review how names are kept, go back to Environment Records.