Appearance
Scope, Hoisting and Closures
7. What is the difference between global scope, function scope, and block scope?
The short answer
Scope is the region of code where a variable can be seen. A variable declared outside every function and block is in global scope and visible everywhere. A variable declared inside a function is in that function's scope and invisible outside it. A variable declared with let or const inside braces, such as an if or a for, is in block scope and only exists inside those braces. var ignores blocks: it is scoped to the whole function.
ts
const storeName = 'Corner Shop' // (1) global
function checkout(items: number[]) {
var discount = 0 // (2) function scope
if (items.length > 3) {
let bonus = 5 // (3) block scope
var note = 'bulk order' // (4) var ignores the block
discount = bonus
}
console.log(note) // 'bulk order'
console.log(bonus) // ReferenceError: bonus is not defined
}
console.log(discount) // ReferenceError: discount is not defined- Global:
storeNamecan be read insidecheckoutand anywhere else. - Function scope:
discountexists only insidecheckout. - Block scope:
bonusexists only between the braces of theif. varleaks out of the block:notebelongs to the whole function, so it can be read after theif.
Why block scope was added. Before ES2015 only var existed, and the only way to make a private area was a function. let and const let you keep a variable as close to its use as possible, which prevents accidental reuse and the loop bug in question 12.
Global scope in practice. In a browser, top-level var and function declarations in a classic script become properties of window. In ES modules and Node.js files, top-level variables are scoped to the module, so they do not pollute anything global. Keep globals to a minimum: any code anywhere can change them, and name clashes are hard to find.
The rule of thumb for interviews: use const by default, let when the value must change, and never var in new code.
8. What are lexical scope and the scope chain?
The short answer
Lexical scope means a function's access to variables is decided by where the function is written in the source code, not by where it is called from. Each scope keeps a link to the scope around it. When code uses a variable, the engine looks in the current scope first, then follows the links outward, one scope at a time, up to the global scope. That series of links is the scope chain. If the name is not found anywhere, you get a ReferenceError.
"Lexical" means "about the text". You can tell which variables a function can see just by reading where it sits in the file.
ts
const currency = 'GBP' // (1)
function makeReceipt(orderId: string) {
const header = `Order ${orderId}` // (2)
function line(price: number) {
return `${header}: ${price} ${currency}` // (3)
}
return line(42)
}
console.log(makeReceipt('A17')) // Order A17: 42 GBP- Global scope holds
currency. makeReceipt's scope holdsheaderandline.- Inside
line, the engine looks forheader: not inline's own scope, so it follows the link tomakeReceipt's scope and finds it there. Forcurrency, it goes one more step out, to the global scope.
Lexical, not dynamic. Where a function is called does not matter:
ts
const label = 'outer'
function show() {
console.log(label)
}
function run() {
const label = 'inner'
show() // prints 'outer', not 'inner'
}
run()show was written in the global scope, so its chain goes from show straight to global. The label inside run is never on show's chain.
Shadowing. A variable in an inner scope with the same name as an outer one hides the outer one inside that scope. The search stops at the first match.
Lexical scope is what makes closures possible, because a function remembers the scopes it was written inside, even after they finish running (question 11).
9. What is hoisting, and how does it differ for var, let, and const?
The short answer
Hoisting is the effect of the engine registering declarations before running any code in a scope. Function declarations are hoisted completely, so you can call them above where they are written. var declarations are hoisted and set to undefined, so reading one early gives undefined. let, const and class are hoisted too, but stay uninitialised until their line runs, so touching them early throws a ReferenceError. That gap is the temporal dead zone.
Nothing is physically moved. In the creation phase of an execution context, the engine scans the scope and reserves a slot for every declaration (question 2). What differs is what each slot holds before its line runs.
| Declaration | Hoisted? | Value before its line | Reading it early |
|---|---|---|---|
function f() {} | Yes, with its body | The function | Works |
var x | Yes | undefined | undefined |
let x | Yes | Uninitialised | ReferenceError |
const x | Yes | Uninitialised | ReferenceError |
class C {} | Yes | Uninitialised | ReferenceError |
const f = () => {} | As a const | Uninitialised | ReferenceError |
Each case in code:
ts
console.log(applyTax(100)) // (1) 120
function applyTax(amount: number) {
return amount * 1.2
}
console.log(discount) // (2) undefined
var discount = 10
console.log(shipping) // (3) ReferenceError: Cannot access 'shipping' before initialization
let shipping = 5
formatPrice(3) // (4) ReferenceError
const formatPrice = (n: number) => `£${n}`- Function declaration: fully hoisted, so the call works.
var: the slot exists and holdsundefined, so the read silently givesundefined. This hides bugs.let: the slot exists but is in the temporal dead zone until linelet shipping = 5runs (question 10).- Arrow function in a
const: it is aconst, so it followsconstrules, not function rules.
Why let and const throw instead. Reading a variable before it has a value is almost always a bug. var hides that bug by returning undefined. let and const make it loud.
10. What is the temporal dead zone?
The short answer
The temporal dead zone is the time between entering a scope and reaching the line that declares a let, const or class variable. During that time the variable exists but has no value, and any access to it throws a ReferenceError. It is "temporal" because it is about when the code runs, not where it is written: a function can safely refer to the variable as long as it is called after the declaration line has run.
ts
{
// dead zone for `orderCount` starts here
const getCount = () => orderCount // (1) fine: only a reference, not run yet
// console.log(orderCount) // (2) would throw: still in the dead zone
let orderCount = 3 // (3) dead zone ends
console.log(getCount()) // (4) 3
}- Writing a reference inside a function is fine, because the function body does not run yet.
- Reading it here would throw, because the declaration line has not run.
- The dead zone ends when this line runs and the variable gets its value.
- Calling the function now works, because by the time it runs, the variable is initialised.
A subtle case: shadowing in the same scope.
ts
const rate = 0.2
function price(amount: number) {
console.log(rate) // ReferenceError, not 0.2
const rate = 0.1
return amount * rate
}The inner const rate is hoisted to the top of price's scope, so it shadows the outer rate from the first line of the function. The first line reads the inner one, which is still in its dead zone.
Why it exists. It makes const meaningful: a const must never be seen with two different values, first undefined and then the real one. The dead zone guarantees nobody can read it before it has its only value.
11. What is a closure, and when is it useful?
The short answer
A closure is a function together with the variables from the scope where it was created. Because of lexical scope, an inner function can use its outer function's variables, and it keeps that access even after the outer function has returned. Closures are how JavaScript gives you private state, function factories, callbacks that remember context, memoisation, and module-like encapsulation without classes.
The idea in one example, a counter for an order ID generator:
ts
function createOrderIdGenerator(prefix: string) {
let next = 1 // (1)
return function nextId() { // (2)
const id = `${prefix}-${String(next).padStart(4, '0')}`
next += 1 // (3)
return id
}
}
const webOrders = createOrderIdGenerator('WEB') // (4)
const shopOrders = createOrderIdGenerator('SHOP')
console.log(webOrders()) // WEB-0001
console.log(webOrders()) // WEB-0002
console.log(shopOrders()) // SHOP-0001 // (5)- A local variable of the outer function.
- The inner function is returned, not called.
- It changes
next, even thoughcreateOrderIdGeneratorhas already returned. - Each call to the outer function creates a new scope, with its own
nextandprefix. - The two generators do not share state: each closure holds its own scope.
Why the variables survive. Normally a function's local variables are freed when it returns. But here the returned function still refers to that scope, so the garbage collector cannot free it (question 4). The scope lives as long as the closure does.
Where closures are used every day:
| Use | Example |
|---|---|
| Private state | The counter above: nothing outside can change next directly |
| Function factories | createOrderIdGenerator('WEB') makes a configured function |
| Callbacks that remember | An event handler that knows which order it belongs to |
| Memoisation | A cache hidden inside a function (question 21) |
| Debounce and throttle | The timer ID lives in a closure (question 92) |
| React hooks | Event handlers in a component close over its props and state |
Closures capture variables, not values. A closure sees the variable's current value when it runs, not the value at the time it was created. That is why the counter keeps counting, and it is also the cause of the loop puzzle in question 12 and of stale state in React event handlers.
12. Why does a loop with var and setTimeout print the same number every time?
The short answer
Because var is function-scoped, the whole loop shares one variable i. The timer callbacks are closures over that single variable, and they only run after the loop has finished, when i has already reached its final value. With let, each loop iteration gets its own new binding of i, so each callback closes over a different variable and prints the value from its own iteration.
The puzzle:
ts
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log('retry', i), 100)
}
// retry 4
// retry 4
// retry 4Step by step:
- The loop runs three times very fast, scheduling three timers.
- There is only one
ifor the whole function, becausevarignores the loop's block. - After the third pass,
i++makes it4, the condition fails, and the loop ends. - 100 milliseconds later, the three callbacks run. Each reads the same
i, which is now4.
The fix with let:
ts
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log('retry', i), 100)
}
// retry 1
// retry 2
// retry 3var, every callback looks at the same box, which says 4 by the time they run. With let, each loop pass creates a fresh box, so each callback keeps its own number.Why let works. The language rule for for (let …) creates a new binding of i for every iteration, copying the previous value into it. Each callback closes over its own binding.
The old fix, before let, was an IIFE that captured the value in a new function scope (question 13):
ts
for (var i = 1; i <= 3; i++) {
((n) => setTimeout(() => console.log('retry', n), 100))(i)
}What the interviewer is really checking: that you understand closures capture variables, not values, and that you know the difference between function scope and block scope.
13. What is an IIFE, and why was it used?
The short answer
An IIFE, an immediately invoked function expression, is a function that is defined and called in the same expression, such as (function () { … })(). Before modules and block scope existed, it was the standard way to create a private scope: variables inside it could not leak into the global scope or clash with other scripts. Today, ES modules and let/const cover most of that need, but IIFEs still appear for one-off async code at the top level of old scripts.
ts
const cartModule = (function () { // (1)
const items: string[] = [] // (2)
return { // (3)
add(sku: string) { items.push(sku) },
count() { return items.length },
}
})() // (4)
cartModule.add('sku-42')
console.log(cartModule.count()) // 1
console.log(cartModule.items) // undefined: private- The parentheses make it an expression, not a declaration, so it can be called immediately.
- Private variable: only the returned functions can reach it, through a closure (question 11).
- Returns a public interface: this is the old "module pattern".
- Calls it at once, so
cartModuleholds the returned object.
Where you still see them:
- Old browser scripts and libraries bundled into one file.
- Async code at the top of a CommonJS file, where top-level
awaitis not allowed:(async () => { await connectDb(); })().
In modern code, an ES module gives every file its own scope, which is the clean replacement (question 66).
14. Can closures cause memory leaks?
The short answer
Yes. A closure keeps its whole surrounding scope alive for as long as the closure itself is reachable. If a long-lived object, such as a global cache, an event emitter, a timer or a DOM element, holds a closure, everything that closure can reach stays in memory too, even data the closure never uses. The fix is to remove listeners and timers when you are done, avoid capturing large objects you do not need, and bound the size of caches.
A typical leak, in a Node.js service:
ts
import { EventEmitter } from 'node:events'
const orderEvents = new EventEmitter() // (1) lives forever
function handleRequest(req: { body: Buffer }) {
const payload = req.body // (2) maybe 5 MB
orderEvents.on('order-paid', () => { // (3)
console.log('paid', payload.length)
})
}- A module-level emitter, alive for the whole life of the process.
- A large value in the request's scope.
- A new listener on every request, never removed. Each listener is a closure that keeps its
payloadalive. After 10,000 requests, 10,000 payloads stay in memory. Node.js prints aMaxListenersExceededWarningafter 10 listeners on one event, which is often the first clue.
The fix:
ts
function handleRequest(req: { body: Buffer }) {
const size = req.body.length // (1)
orderEvents.once('order-paid', () => { // (2)
console.log('paid', size)
})
}- Capture only what you need, a number, not the whole buffer.
onceremoves the listener after it runs. In other cases, callofforremoveListenerwhen the work is finished, or use anAbortSignalto remove listeners in bulk.
Other common closure leaks:
| Source | Leak | Fix |
|---|---|---|
setInterval callback | Never cleared, keeps its scope forever | clearInterval when done |
| DOM event listener | Removed element still referenced by a listener | removeEventListener, or an AbortController signal |
| Unbounded cache in a closure | Grows with every new key | Size limit or LRU (question 102) |
| React effect | Subscription never cleaned up | Return a cleanup function from the effect |
How to find such leaks with heap snapshots is covered in the Node.js memory questions.