Intermediate Interview Questions
What is a closure? Give a use case.
A function that remembers the variables of the scope where it was created, even after that scope has finished. Uses: private state, function factories, memoization, event handlers that need context.
Example
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next(), next(), next());Output
1 2 3
Explain this in JavaScript.
this is decided by how a function is called: the object before the dot for methods, the new instance with new, the first argument of call/apply/bind, undefined (strict) or the global object for plain calls, and the enclosing this for arrow functions.
What is the event loop?
JavaScript runs on one thread. Async work is done outside it; when finished, callbacks are queued. When the call stack is empty, the event loop first runs all microtasks (promise callbacks), then one task (timers, events), and repeats. That is why a resolved promise runs before setTimeout(fn, 0).
Promise vs async/await?
async/await is syntax on top of promises. An async function always returns a promise, and await pauses it until a promise settles. It makes sequential async code read like synchronous code and lets you use try/catch for errors.
map vs forEach vs filter vs reduce?
| Method | Returns | Use |
|---|---|---|
| forEach | undefined | side effects (logging, DOM updates) |
| map | new array of the same length | transform each element |
| filter | new array with matching elements | select |
| reduce | any single value | combine into a total/object |
Shallow copy vs deep copy?
A shallow copy ({...obj}, Object.assign, arr.slice()) copies only the top level; nested objects are shared. A deep copy (structuredClone(obj)) duplicates everything.
What is event delegation?
Attaching one listener to a parent instead of one per child, then using event.target to see which child was clicked. It uses event bubbling, saves memory, and works for children added later.
Debounce vs throttle?
Debounce runs a function once after calls have stopped for N ms (search box). Throttle runs it at most once every N ms while calls continue (scroll, resize).