Appearance
How JavaScript Runs
1. What is JavaScript, and how does its runtime execute code?
The short answer
JavaScript is a single-threaded, dynamically typed language that runs inside a host, such as a browser or Node.js. The engine, for example V8, parses your code, compiles it to machine code on the fly, and runs it on one call stack, storing objects in a memory heap. The host adds everything else: timers, network, files, the DOM, and an event loop that feeds finished background work back to the engine as callbacks.
Think of a restaurant with one chef. The chef can only cook one dish at a time. That is the engine with its single call stack. The restaurant also has helpers: someone watching the oven timer, someone answering the phone, someone fetching deliveries. Those are the host's APIs. When a helper finishes, they put a note on the chef's queue, and the chef handles it as soon as the current dish is done. That queue and the rule for picking notes from it is the event loop.
What happens when a script runs, step by step:
- Parse. The engine reads the source text and builds a tree of the program, called an abstract syntax tree.
- Compile. It turns that tree into bytecode, a compact set of instructions, and starts running it at once. Hot code is later compiled to fast machine code (question 5).
- Create the global execution context. The engine sets up the global scope and registers every declared function and variable (question 2).
- Run top to bottom on the call stack. Each function call pushes a frame; each return pops it (question 3).
- Hand off slow work. A
setTimeout,fetchor file read is passed to the host. The engine does not wait for it. - Run callbacks later. When the stack is empty, the event loop takes finished callbacks from the queues, one at a time.
An example, in a checkout page:
ts
console.log('1. start checkout') // (1)
setTimeout(() => { // (2)
console.log('3. timer fired')
}, 0)
fetch('/api/cart').then(() => console.log('4. cart loaded')) // (3)
console.log('2. checkout code finished') // (4)- Runs at once on the call stack.
- Hands a timer to the host. Even with
0milliseconds, the callback waits until the stack is empty. - Hands a network request to the host. Its callback runs whenever the response arrives.
- Runs at once, before either callback.
It prints 1, then 2, then 3, and 4 whenever the network answers, usually last. The order of 3 and 4 is explained in the event loop questions (question 60).
Single-threaded, but not slow. Only one piece of your JavaScript runs at a time. But waiting for a network response or a file does not block anything, because that waiting happens in the host. This is why one Node.js process can serve thousands of connections.
Dynamically typed means a variable has no fixed type: let total = 5 can later hold 'five'. Types are checked while the code runs, not before. TypeScript adds checking before the code runs (question 70).
2. What is an execution context?
The short answer
An execution context is the environment in which a piece of code runs: it holds that code's variables, its functions, the value of this, and a link to the outer scope. There is one global execution context, and a new one is created every time a function is called. Each context is built in two phases: a creation phase, which sets up memory for its variables and functions, and an execution phase, which runs the code line by line.
Picture each function call as a fresh desk with its own notepad. The notepad holds the function's own variables. The desk also has a note saying "if you cannot find something here, look on the desk next door", which is the link to the outer scope. When the function returns, the desk is cleared away.
The three kinds:
| Kind | Created when | Example |
|---|---|---|
| Global | The script starts | Top-level code of a file |
| Function | A function is called | Every call to applyDiscount() |
| Eval | eval() runs code | Rare, and best avoided |
What a context contains:
- Variable environment: the variables and function declarations of that code.
- Lexical environment: the same idea for
let,constand blocks, plus a link to the outer environment. This link is what makes the scope chain (question 8). thisbinding: whatthismeans in that code (question 15).
The two phases, on a real snippet:
ts
function applyDiscount(price: number) {
const rate = 0.1 // (1)
return price - price * rate
}
const total = applyDiscount(200) // (2)
console.log(total) // (3)- Inside the function's context,
rateis reserved in the creation phase, then given0.1when that line runs. - Calling
applyDiscountcreates a new function context and pushes it on the call stack (question 3). - Back in the global context,
totalis180, which is printed.
Why the creation phase matters. Because variables and functions are registered before any line runs, you can call a function declared further down the file. That effect is called hoisting (question 9).
3. What is the call stack?
The short answer
The call stack is the engine's list of functions that are currently running, last in, first out. Calling a function pushes a frame onto the top; returning pops it off, and the engine continues with the frame underneath. Because there is only one stack, only one function runs at a time. If calls nest too deep, for example in endless recursion, the stack overflows and you get "Maximum call stack size exceeded".
Last in, first out works like a stack of plates. You add plates on top and take them from the top. The plate you put down last is the first you pick up.
ts
function formatPrice(amount: number) {
return `£${amount.toFixed(2)}` // (3)
}
function lineTotal(qty: number, unitPrice: number) {
return formatPrice(qty * unitPrice) // (2)
}
console.log(lineTotal(3, 4.5)) // (1)lineTotal(3, 4.5)is pushed on top of the global frame.- It calls
formatPrice(13.5), which is pushed on top. formatPricereturns"£13.50"and is popped. ThenlineTotalreturns it and is popped. The global code prints£13.50.
A frame holds that call's arguments, its local variables and where to return to.
Stack traces read this list. When an error is thrown, the stack trace prints the frames from top to bottom, which is why the first line names the function that failed and the lines below show who called it:
text
Error: card declined
at chargeCard (payments.ts:12:11)
at placeOrder (orders.ts:40:5)
at handleCheckout (routes.ts:18:3)Stack overflow. The stack has a size limit. A function that calls itself with no stopping condition keeps pushing frames until the limit is hit:
ts
function countItems(n: number): number {
return countItems(n + 1) // no base case: never stops
}
countItems(0)
// RangeError: Maximum call stack size exceededWhy "only one stack" matters. While a long function is running, nothing else can run: no clicks are handled, no other requests are served, no timers fire. This is why heavy work must be split up or moved to another thread (question 65).
4. What is the memory heap?
The short answer
The heap is the large, unordered area of memory where the engine stores objects, arrays, functions and closures, anything whose size or lifetime is not fixed. The call stack holds small, short-lived values and references, which are addresses pointing into the heap. Memory on the heap is freed automatically by the garbage collector once nothing can reach an object any more.
Stack and heap side by side:
| Call stack | Heap | |
|---|---|---|
| Holds | Frames: local primitives and references | Objects, arrays, functions, closures |
| Organised as | Ordered, last in first out | Unordered pool |
| Size | Small, fixed limit | Large, grows as needed |
| Freed | When the function returns | When the garbage collector finds it unreachable |
ts
function addToCart(cart: { items: string[] }, sku: string) {
const qty = 2 // (1)
cart.items.push(sku) // (2)
}qtyis a number, a primitive. It is small and fixed, so it sits in the function's frame.cartis a reference. The frame only holds the address. The object, and itsitemsarray, live on the heap. WhenaddToCartreturns, its frame disappears, but the cart stays on the heap because other code still refers to it.
Primitives versus objects. Copying a number copies the value. Copying an object variable copies the reference, so both variables point at the same object:
ts
const original = { total: 100 }
const copy = original // same object, not a new one
copy.total = 0
console.log(original.total) // 0That is the root of the shallow versus deep copy question (question 45).
Garbage collection. The engine periodically finds objects that nothing can reach, starting from the global object and the current stack frames, and frees their memory. You never free memory by hand, but you can still leak it by keeping references you no longer need, such as an ever-growing cache or a forgotten event listener. In V8, most objects die young, so new objects go into a small "young generation" that is cleaned often and quickly. Survivors move to an "old generation" that is cleaned less often. The Node.js memory questions go deeper into this.
5. Is JavaScript interpreted or compiled, and what is JIT compilation?
The short answer
Modern engines do both. They first compile your code quickly to bytecode and interpret that, so the program starts at once. While it runs, they watch which functions are "hot", called very often, and compile those to optimised machine code in the background. That is just-in-time, or JIT, compilation. If the assumptions behind the optimised code break, for example a function suddenly receives a string instead of a number, the engine throws that code away and falls back to the bytecode.
V8's pipeline, simplified:
| Stage | V8 name | Does |
|---|---|---|
| Parser | Source text into a syntax tree | |
| Interpreter | Ignition | Runs bytecode at once, collects type feedback |
| Fast optimiser | Sparkplug, Maglev | Quick machine code for warm functions |
| Full optimiser | TurboFan | Highly optimised machine code for hot functions |
Type feedback is the key idea. While the bytecode runs, the engine notes what types each operation saw. If addTax(price) was always called with numbers, the optimiser can generate machine code that assumes numbers and skips the checks.
Deoptimisation:
ts
function addTax(price) {
return price * 1.2
}
for (let i = 0; i < 100_000; i++) addTax(i) // (1)
addTax('19.99') // (2)- Hot and always numbers, so V8 optimises
addTaxfor numbers. - A string arrives. The assumption breaks, V8 deoptimises the function and goes back to the slower general path.
What this means in practice:
- Keep functions monomorphic, called with the same shapes of data, in hot paths.
- Create objects with the same properties in the same order, so the engine can share one hidden layout, called a hidden class or shape, between them.
- Do not micro-optimise without measuring. The engine is good at this, and a profiler shows what is really slow.
6. What is strict mode, and what does it change?
The short answer
Strict mode, turned on with 'use strict' at the top of a file or function, makes JavaScript reject several silent mistakes. Assigning to an undeclared variable throws instead of creating a global, this is undefined in a plain function call instead of the global object, duplicate parameter names are errors, and writes to read-only properties throw. ES modules and class bodies are always in strict mode, so most modern code already runs strict.
The most important changes:
| Situation | Sloppy mode | Strict mode |
|---|---|---|
totl = 5 with a typo, never declared | Creates a global variable | ReferenceError |
this in a plain function call | The global object | undefined |
| Writing to a frozen object | Silently ignored | TypeError |
function f(a, a) {} | Allowed | SyntaxError |
delete of a plain variable | Silently ignored | SyntaxError |
with statement | Allowed | SyntaxError |
The typo example:
ts
'use strict'
function calculateTotal(items: number[]) {
let total = 0
for (const price of items) {
totl += price // typo: ReferenceError: totl is not defined
}
return total
}Without strict mode, totl would silently become a global variable, and the function would return 0 with no error.
Where it is on automatically:
- Every ES module file, using
importandexport(question 66). - Every class body.
- TypeScript emits
'use strict'for you when it compiles to CommonJS with thealwaysStrictoption, whichstrict: trueturns on.
So in a modern codebase, the main place sloppy mode still appears is old scripts loaded with a plain <script> tag, or old CommonJS files without the directive.