Advanced Interview Questions
Explain prototypal inheritance.
Every object has an internal link to another object, its prototype. Property lookups walk this chain until found or until null. Classes are syntax over this: class B extends A sets B.prototype's prototype to A.prototype.
Microtasks vs macrotasks?
Microtasks: promise callbacks, await continuations, queueMicrotask. Macrotasks: setTimeout, setInterval, I/O, UI events. After each macrotask the engine drains the entire microtask queue before rendering or taking the next macrotask.
How do you prevent memory leaks?
- Clear intervals and timeouts you no longer need.
- Remove event listeners (or use an AbortController signal).
- Avoid unbounded caches; use WeakMap for object-keyed metadata.
- Drop references to removed DOM nodes.
- Profile with DevTools heap snapshots.
What are generators and iterators?
An iterator is an object with a next() method returning { value, done }; for...of uses it. A generator (function*) creates iterators easily: it pauses at each yield and resumes on the next next() call, enabling lazy sequences.
Implement Promise.all yourself.
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let done = 0;
if (promises.length === 0) return resolve(results);
promises.forEach((p, i) => {
Promise.resolve(p).then((value) => {
results[i] = value; // keep the original order
if (++done === promises.length) resolve(results);
}, reject); // first rejection rejects all
});
});
}What is the difference between CommonJS and ES modules?
CommonJS (require/module.exports) loads synchronously at runtime and is the Node.js legacy format. ES modules (import/export) are static, so tools can analyse and tree-shake them; they are asynchronous, strict by default and support top-level await.