JavaScript Interview Questions
Practice language fundamentals, object behavior, asynchronous execution, and practical browser-side coding decisions.
Explained JavaScript questions
How do lexical scope, hoisting, closures, var, let, and const relate?
Lexical scope is determined by where code is written. A closure is a function together with access to bindings in its surrounding lexical environment. var is function-scoped and initialized to undefined during declaration processing; let and const are block-scoped and cannot be accessed before initialization in their temporal dead zone. const prevents reassignment of the binding, not mutation of an object it references.
Example
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2
Why it works
The returned function keeps access to the same lexical binding after makeCounter has returned. Each call to makeCounter creates a separate environment.
Common mistakes
- Saying let and const are not hoisted; their bindings exist but are inaccessible in the temporal dead zone.
- Assuming a const object is deeply immutable.
- Using var in a loop and expecting each callback to capture a separate block binding.
Follow-up questions
- How can a closure accidentally retain large objects?
- What does the temporal dead zone prevent?
Real-world use
Closures support encapsulated state and callbacks, but long-lived listeners should release references when no longer needed.
Further reading: MDN: Closures · MDN: let
How do prototypes and this work, including call, apply, and bind?
Objects can delegate property lookup through a prototype chain. A constructor's prototype is shared by instances created with new, while an object's internal prototype points to the next lookup object. The value of this is determined by how a function is called, not simply where it was defined. call invokes with a chosen receiver and separate arguments; apply accepts an argument array-like value; bind returns a function with a fixed receiver and optionally preset arguments.
Example
const user = { name: 'Rae' };
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
greet.call(user, 'Hello'); // 'Hello, Rae'
const sayHello = greet.bind(user, 'Hello');
sayHello(); // 'Hello, Rae'
Why it works
The explicit receiver passed to call or bind provides the this value for this ordinary function invocation. Arrow functions instead capture this lexically.
Common mistakes
- Assuming an extracted method keeps its original object as this.
- Using an arrow function when a method needs a dynamic receiver.
- Confusing a constructor's prototype property with an instance's prototype link.
Follow-up questions
- How does class syntax use prototypes?
- Why can a callback passed to a timer lose its receiver?
Real-world use
Understanding receivers helps debug event handlers and callbacks; prototype lookup also explains shared methods and inherited properties.
Further reading: MDN: Inheritance and the prototype chain · MDN: this
What happens when JavaScript runs promises and async/await, and how does coercion affect equality?
An async function always returns a promise; await suspends that function until its operand settles, without blocking the JavaScript thread. Promise reactions run as microtasks after the current synchronous stack. The event loop later processes other tasks such as timers. Strict equality (===) avoids most implicit conversions, while == applies coercion rules that can be surprising; conversion also occurs in conditions and arithmetic.
Example
console.log('start');
Promise.resolve().then(() => console.log('promise job'));
setTimeout(() => console.log('timer task'), 0);
console.log('end');
// start, end, promise job, then timer task
0 == false; // true
0 === false; // false
Why it works
Synchronous statements finish before promise jobs are drained. A timer callback is a later task, and strict equality compares without the loose-equality conversion step.
Common mistakes
- Treating await as a way to make CPU-heavy work parallel.
- Forgetting to await or return a promise inside error-handling code.
- Using loose equality when the intended conversion is not explicit.
Follow-up questions
- How do Promise.all and Promise.allSettled differ on rejection?
- When can microtasks delay rendering or other tasks?
Real-world use
Use structured async error handling for API requests and prefer explicit parsing at data boundaries over relying on coercion.
Further reading: MDN: Using promises · MDN: Equality comparisons
How would you implement debouncing, throttling, and avoid memory leaks in an interactive page?
Debouncing delays work until calls stop for a chosen interval, which suits search input. Throttling limits work to at most a chosen frequency, which suits scroll or resize updates. Both should have clear cancellation and cleanup behavior. Memory leaks often come from retained DOM nodes, unremoved listeners, timers, or closures holding large data after a component or page is done with them.
Example
function debounce(fn, delay) {
let timer;
function wrapped(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
}
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}
const onSearch = debounce(search, 250);
input.addEventListener('input', onSearch);
// On teardown: input.removeEventListener('input', onSearch); onSearch.cancel();
Why it works
Clearing the previous timer coalesces rapid calls. Explicitly removing the same listener and cancelling pending work releases references and prevents stale callbacks.
Common mistakes
- Creating a new debounce wrapper on every event, so the old timer is never cleared.
- Forgetting to preserve this or arguments when wrapping a function.
- Leaving listeners or timers active after the owning UI is removed.
Follow-up questions
- How would you add leading-edge behavior or a maximum wait?
- How can heap snapshots help confirm a suspected leak?
Real-world use
Use debounce for text search, throttle for high-frequency visual updates, and profile before changing memory-management behavior.
Further reading: MDN: EventTarget.removeEventListener · Chrome DevTools: Memory problems
How does the JavaScript event loop schedule promise callbacks and timers?
The current JavaScript stack runs to completion before queued work is processed. Promise reactions are microtasks; timers schedule tasks that become eligible after a delay, not at an exact guaranteed time. Browsers generally drain microtasks before moving to another task and may render between tasks, but scheduling details differ between browser and server runtimes.
Example
console.log('A');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('B');
// A, B, promise, timer
Why it works
The synchronous statements finish first. The promise reaction is then processed as a microtask before the timer callback in this browser example.
Common mistakes
- Saying setTimeout(..., 0) runs immediately or at an exact time.
- Treating browser and Node.js event-loop phase details as identical.
- Queuing unbounded microtasks, which can delay rendering and other tasks.
Follow-up questions
- How can a long task affect input responsiveness?
- When would requestAnimationFrame be preferable to a timer?
Real-world use
This ordering helps diagnose UI stalls, delayed rendering, and tests that need to wait for asynchronous updates.
Further reading: MDN: JavaScript execution model · MDN: Microtasks