JavaScript closure interview questions.
Closures are the most asked JavaScript concept, because so much is built on them: private state, function factories, once, memoize, debounce and every React hook. These questions start with predicting what scope and loop snippets print, then have you write the utilities that depend on closures, then fix the stale closures that catch people out in React.
8 of these questions have free answers; the rest are in Pro. Updated .
58
questions
- Easy
- 20
- Medium
- 36
- Hard
- 2
What interviewers look for
- You can say what a closure captures: the variable itself, not a copy of its value.
- You explain the var loop bug and fix it with let, a function argument or bind.
- You use closures for private state and know the memory they keep alive.
- You spot a stale closure in a hook and fix it with dependencies, a ref or a state updater.
Concept questions, answered
The definitions and comparisons interviewers open with. Free to read, each with a full answer and examples.
What is a closure in JavaScript?
A closure is a function together with the variables from the scope where it was created. In JavaScript every function keeps a live reference to its surrounding scope, so it can read and update those variables even after the outer function has returned. That is how private state, function factories, once, debounce and memoize work.
What is lexical scope and the scope chain in JavaScript?
Lexical scope means the variables a piece of code can see are decided by where that code is written in the source, not by where it is called from. Scopes nest: global, then functions, then blocks. When you use a name, JavaScript looks in the current scope, then the one around it, and so on outward to the global scope. That ordered list of scopes is the scope chain.
What is the difference between var, let and const?
var is function scoped, can be redeclared and is hoisted with the value undefined. let and const are block scoped, cannot be redeclared in the same scope and cannot be used before their declaration. let can be reassigned, while const cannot be rebound. Use const by default, let when you must reassign, and avoid var.
What is hoisting in JavaScript?
Hoisting is how JavaScript registers declarations before it runs any code in a scope. The engine reads the whole scope first and creates the names, so you can use some of them above the line that declares them. Function declarations are fully usable early, var gives you undefined, and let, const and class throw an error.
What is an IIFE in JavaScript?
An IIFE (immediately invoked function expression) is a function that is defined and called in the same expression, such as (function () { ... })(). It runs once, straight away, and gives the code inside its own scope. Before let, const and ES modules, that was the only way to keep variables private instead of leaking them into the global scope.
What is currying in JavaScript?
Currying turns a function that takes several arguments into a chain of functions that each take one, so f(a, b, c) becomes f(a)(b)(c). Each call returns a new function until all arguments have arrived. It works through closures and makes it easy to build specialised functions from general ones.
How does the this keyword work in JavaScript?
In JavaScript, this is decided by how a function is called, not where it is written. A method call obj.fn() sets this to obj, new Fn() sets it to the new object, call, apply and bind set it explicitly, and a plain call leaves it undefined in strict mode. Arrow functions ignore these rules and use the this of the code around them.
Easy20
- Implement
Function., including partial argumentsFreeImplement Function.prototype.myBind(thisArg, ...boundArgs) without using the built-in bind. It returns a new function…prototype. bind() - Implement a
once()function using closuresImplement once(fn). It returns a new function that calls fn the first time it is called and returns its result. Every… - Implement a countdown timer with pause, resume and resetImplement two functions:
- Fix the
varloop closure bug three waysThis function should log 0, 1, 2, …, n - 1, but it doesn't: - Predict hoisting and TDZ results for functions,
var,let,constandclassFreeRead each snippet and write down exactly what it logs, without running it. When a line throws, the snippet logs the… - Implement
clearAllTimeouts()by tracking pending timersBrowsers have no built-in way to cancel every pending timeout. Make one: after your code loads, any timeout created with… - Predict closure results: counters, loops, captured variables and lexical scope"What does this print?" questions about closures appear in almost every JavaScript interview. Read each snippet and…
- Implement infinite currying:
sum(1)(2)(3)()One of the most asked JavaScript interview questions: write sum so it can be called any number of times and returns the… - Write small function utilities:
myAt,myWith,square, argument counts,makeCounter,cycleand a singletonPhone screens often chain several tiny tasks to check that you know prototypes, closures and how functions count their… - Avoid stack overflow in deep recursion with a trampolineEvery call adds a frame to the call stack, and after some thousands of frames (the exact limit depends on the engine and…
- Predict
1 + functioncoercion, and overridetoStringwith an IIFE and a closureA puzzle reported in public interview write-ups starts with console.log(1 + function x() { ... }) and then asks you to… - Predict strict mode versus sloppy mode results: implicit globals,
this, frozen objects andargumentsModules and classes are always strict, but plenty of code (scripts, inline handlers, older libraries, consoles) still… - Predict scope puzzles: named function expressions, the
catchparameter, default-parameter scope and shadowingScope questions go beyond var versus let: they test the small scopes that hide in function expressions, catch clauses,… - Predict which function declaration wins: duplicates, code after
returnand functions inside blocksInterviewers like a tiny snippet where a function is declared twice and one of the declarations sits after a return. The… - Predict the output of loop, timer, promise, hoisting and closure snippetsA JavaScript screening round often ends with a handful of short snippets: "what does this log?" Predict what each one…
- Implement
computeAmount()with chainablecrore(),lacs()andthousand()calls and a finalvalue()Indian amounts are often spoken as a mix of crores, lakhs and thousands: "5 crore 15 lakh 45 thousand". Write… - Predict quick-fire results: a detached method, a shadowed
let, a shallowObject.,freeze Promise.andresolve(fn) -0A JavaScript round often opens with short snippets and the question "what does this log?". This set has been reported in… - Implement Redux Toolkit's
createAction()with prepare callbacks,.match()and theisAnyOfandisAllOfmatchersHand-written Redux code repeats every action type twice: once as a constant, once inside an action creator. Redux… - Compose product filters with the Specification pattern:
and,or,notand a readable summaryA shop's filter panel combines rules such as "in stock", "price under 2000" and "by Philips". Writing one big filter… - Build an array iterator with
next(),done(),peek(),reset()andfor...ofsupportInterviewers often open with a small helper that walks an array one item at a time, then ask how it relates to…
Medium36
- Implement debounce() with
cancel()andflush()FreeImplement debounce(fn, wait). It returns a debounced function that delays calling fn until wait milliseconds have passed… - Implement
throttle()with leading and trailing optionsFreeImplement throttle(fn, wait, { leading = true, trailing = true } = {}). The throttled function calls fn at most once per… - Implement
curry()supporting partial applicationFreeImplement curry(fn). It returns a curried version of fn that keeps collecting arguments until it has at least fn.length… - Implement
memoize()with custom cache keysFreeImplement memoize(fn, resolver). It returns a function that caches the results of fn, so calling it again with the same… - Implement
useInterval()without stale closuresFreeThis counter looks right but gets stuck at 1: - Implement
useEventListener()anduseClickOutside()without re-subscribing every renderImplement two React hooks, useEventListener and useClickOutside, that attach DOM listeners once instead of… - Implement
cva()(class-variance-authority) for component variantsDesign systems built with Tailwind (shadcn/ui and many others) describe a component's styles with cva. Implement… - Build a mini test runner with
describe,it, hooks and timeoutsJest and Vitest feel like magic until you build one. Implement createTestRunner(), which returns { describe, it,… - Build a small state-machine library with guards, actions and subscriptionsUI flows (checkout, file upload, auth) are easier to get right as explicit state machines, which is what XState…
- Implement
useTimeout()with reset, clear and the latest callbackAuto-dismissing toasts, "undo" windows and delayed tooltips all need a timeout tied to a component. Implement… - Predict stale closure results in React: timeouts, intervals and event handlers"What is a stale closure in React?" is one of the most searched React questions, and interviewers test it with code.…
- Fix five React bugs: stale interval, missing dependency, mutated state, missing provider and a strict search"Here is some code that does not work, find out why" is a common React round. The five components below each contain one…
- Implement
promiseMerge()and cancellablesetTimeoutandsetIntervalTwo small async utilities that interviewers pair together: one combines two promises, the other wraps timers so callers… - Implement
debounce()withleading,trailingandmaxWait, pluscancel(),flush()andpending()Question 26 builds a trailing-only debounce with cancel() and flush(). Real code needs the options Lodash offers: fire… - Implement
curry()with placeholders that later calls fill left to rightQuestion 28 builds curry(fn) that collects arguments in order. Lodash and Ramda also let you skip an argument with a… - Write call-control wrappers:
sampler(),before(),after()and atimed()that keeps sync and async resultsA wrapper takes a function and returns one with the same signature plus a rule about when or how it runs. Question 7… - Implement Redux
createStore()with enhancers andapplyMiddleware(): middleware order, thunk and loggerQuestion 64 builds the core of a Redux store and a React binding. The part interviewers dig into next is middleware: the… - Build a pub/sub bus with wildcard topics: one-word
*and multi-word#matchesLarge frontends often share one event bus between features. Topics are dot-separated words like user.42.created, and… - Implement
rafThrottle(): run at most once per animation frame, with cancel and flushscroll, pointermove and resize can fire many times between two screen refreshes. Updating the DOM on each event wastes… - Implement
debouncePromise(): every caller in a burst gets the last call's resultA normal debounce drops the calls it skips, so code like const result = await validate(value) hangs forever for every… - Build
useDebouncedCallback(): a stable debounced function with cancel, flush, maxWait and unmount cleanupuseMemo(() => debounce(save, 500), [save]) looks right but breaks in practice: save is a new function on every render,… - Memoize with expiry and a maximum size, shared across modules that fetch by keyA plain memoize (question 31) keeps every result forever. In a real app that is a memory leak and a source of stale…
- Predict the logs when React state and refs are mixed: batching, closures, timeouts and ref timingA React snippet that uses setState and useRef together several times, with the question "what does it log?", has been…
- Bug squash: make six failing tests of an unfamiliar cart module pass without touching the testsA "bug squash" round has been reported in public interview write-ups: you get an existing codebase with failing unit…
- Implement
memoizeOne()with a custom equality checkA selector or a render helper is often called again and again with the same inputs, but only the latest inputs matter. A… - Memoize a function by argument identity with a tree of Maps and WeakMapsJSON.stringify(args) is a poor cache key: two different objects with the same content collide, functions disappear, and…
- Implement
jest.with call records,spyOn() mockImplementationand restoreTest runners let you watch a method without changing the code under test. Implement spyOn(object, methodName), a small… - Build a tiny
expectwithtoBe,toEqualand a.notchainEvery test runner has an expect. Build a small one, tinyExpect(actual), plus the error class it throws. A matcher that… - Record a
console.history while still printingA support widget wants to attach the last few console messages to a bug report, without hiding them from the developer.…log - Build an interval whose delay grows on every run, with a clear functionA reconnect loop should wait 1 s, then 2 s, then 3 s, and stop as soon as the connection is back. setInterval uses one…
- Implement singleton, factory and strategy patterns idiomatically in JavaScriptA checkout module needs three small building blocks. Write each one with closures and plain objects or Maps; no class…
- Predict
useMemoanduseCallbackcache hits as props and dependencies changeuseMemo and useCallback are often added "for performance" without checking whether they ever return a cached value.… - Implement Redux's
combineReducers()with its shape checks: init probes, undefined results, unexpected keys and reference reusecombineReducers looks like a three-line loop, and question 64 builds that loop. The real one is longer because it is… - Implement Redux Toolkit's
createReducer()builder:addCase,addMatcher,addDefaultCaseand their ordering rulescreateSlice hides most of its work in createReducer, and the part interviewers ask about is the builder in… - Implement
jest.mock functions:fn() mockReturnValueOnce,mockResolvedValue,mock.andresults mockResetjest.fn() (and vi.fn() in Vitest) is the tool interviewers expect you to understand inside out: what it records, which… - Read n characters from a source that only returns four at a time, keeping the leftovers between callsSome sources only give data in fixed chunks: a decoder that emits 4 bytes at a time, a paginated API with a fixed page…
Hard2
- Implement a mini
useStateanduseEffecthooks engineFreeHooks look like magic: how does useState "remember" a value in a plain function? Build a tiny hooks engine to find out. - Simulate ES module evaluation order: cycles, TDZ errors and slow top-level
await"Why does this import crash with Cannot access 'X' before initialization, but only when the app starts from a different…
Practise with tests and full answers.
Every question has a runnable editor, tests and a step-by-step solution. Passes from ₹149, paid once; nothing renews.
Frequently asked
What closure questions are asked in JavaScript interviews?
Define a closure and give an example, predict what a for loop with var and setTimeout prints and fix it, write a counter with private state, implement once, memoize or debounce, explain the module pattern, and in React, explain why a timer or event handler reads an old value of state.
Do closures cause memory leaks?
Only when something long-lived keeps a closure that holds on to large data: an event listener that is never removed, a timer that is never cleared, or a cache that never evicts. Remove the listener, clear the timer, or store less in the closure.
What is a stale closure in React?
A callback that was created during an earlier render and still reads that render's state and props. It shows up in effects with missing dependencies and in intervals. Fix it by adding the dependency, using the functional form of setState, or reading the latest value from a ref.