Skip to content

Interview PrepBasics · Basics

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
  1. Global: storeName can be read inside checkout and anywhere else.
  2. Function scope: discount exists only inside checkout.
  3. Block scope: bonus exists only between the braces of the if.
  4. var leaks out of the block: note belongs to the whole function, so it can be read after the if.
global scope: storeName, checkoutfunction scope of checkout: discount, noteblock scope of the if: bonuscan see bonus, discount, note,storeNamesees outward, never inward:the function cannot read bonus
Boxes inside boxes. Code can read variables from its own box and every box around it. It can never reach into a box inside it.

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
  1. Global scope holds currency.
  2. makeReceipt's scope holds header and line.
  3. Inside line, the engine looks for header: not in line's own scope, so it follows the link to makeReceipt's scope and finds it there. For currency, 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.

DeclarationHoisted?Value before its lineReading it early
function f() {}Yes, with its bodyThe functionWorks
var xYesundefinedundefined
let xYesUninitialisedReferenceError
const xYesUninitialisedReferenceError
class C {}YesUninitialisedReferenceError
const f = () => {}As a constUninitialisedReferenceError

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}`
  1. Function declaration: fully hoisted, so the call works.
  2. var: the slot exists and holds undefined, so the read silently gives undefined. This hides bugs.
  3. let: the slot exists but is in the temporal dead zone until line let shipping = 5 runs (question 10).
  4. Arrow function in a const: it is a const, so it follows const rules, 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
}
  1. Writing a reference inside a function is fine, because the function body does not run yet.
  2. Reading it here would throw, because the declaration line has not run.
  3. The dead zone ends when this line runs and the variable gets its value.
  4. 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)
  1. A local variable of the outer function.
  2. The inner function is returned, not called.
  3. It changes next, even though createOrderIdGenerator has already returned.
  4. Each call to the outer function creates a new scope, with its own next and prefix.
  5. The two generators do not share state: each closure holds its own scope.
webOrdersshopOrdersfunction nextIdcopy 1function nextIdcopy 2remembered scopeprefix "WEB", next 3remembered scopeprefix "SHOP", next 2the outer function has returned; these scopes stay alive
A function carrying a backpack. Each returned function keeps a reference to the scope it was born in. As long as the function exists, so does that scope, and its variables keep their latest values.

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:

UseExample
Private stateThe counter above: nothing outside can change next directly
Function factoriescreateOrderIdGenerator('WEB') makes a configured function
Callbacks that rememberAn event handler that knows which order it belongs to
MemoisationA cache hidden inside a function (question 21)
Debounce and throttleThe timer ID lives in a closure (question 92)
React hooksEvent 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 4

Step by step:

  1. The loop runs three times very fast, scheduling three timers.
  2. There is only one i for the whole function, because var ignores the loop's block.
  3. After the third pass, i++ makes it 4, the condition fails, and the loop ends.
  4. 100 milliseconds later, the three callbacks run. Each reads the same i, which is now 4.

The fix with let:

ts
for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log('retry', i), 100)
}
// retry 1
// retry 2
// retry 3
var: one shared icallback 1callback 2callback 3i = 4let: a new i per iterationcallback 1callback 2callback 3i = 1i = 2i = 3
One box or three. With var, 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
  1. The parentheses make it an expression, not a declaration, so it can be called immediately.
  2. Private variable: only the returned functions can reach it, through a closure (question 11).
  3. Returns a public interface: this is the old "module pattern".
  4. Calls it at once, so cartModule holds 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 await is 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)
  })
}
  1. A module-level emitter, alive for the whole life of the process.
  2. A large value in the request's scope.
  3. A new listener on every request, never removed. Each listener is a closure that keeps its payload alive. After 10,000 requests, 10,000 payloads stay in memory. Node.js prints a MaxListenersExceededWarning after 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)
  })
}
  1. Capture only what you need, a number, not the whole buffer.
  2. once removes the listener after it runs. In other cases, call off or removeListener when the work is finished, or use an AbortSignal to remove listeners in bulk.

Other common closure leaks:

SourceLeakFix
setInterval callbackNever cleared, keeps its scope foreverclearInterval when done
DOM event listenerRemoved element still referenced by a listenerremoveEventListener, or an AbortController signal
Unbounded cache in a closureGrows with every new keySize limit or LRU (question 102)
React effectSubscription never cleaned upReturn a cleanup function from the effect

How to find such leaks with heap snapshots is covered in the Node.js memory questions.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet