Interview questions
JavaScript interview questions and answers
A JavaScript interview checks whether you can predict what code does: types and coercion, scope and this, closures, promises and the event loop. Expect at least one "what does this print" puzzle and a small function to write live.
For live interviews: the FlexQ interview copilot for Mac or Windows, 30 free live minutes.
Updated 2026-11-23 · 22 questions · junior, mid-level, senior and a coding round · a model answer and what the interviewer is checking for each
The answers describe modern JavaScript (ES2015 and later) as it runs in browsers and Node.js. Every code sample here runs as written; try them in the browser console before you rely on them.
Jump to: Junior · Mid-level · Senior · Coding round · How to practice · FAQ
Junior JavaScript questions
Junior questions check the language basics that every later answer builds on.
1. What are the data types in JavaScript?
Model answer: There are seven primitive types: string, number, bigint, boolean, undefined, symbol and null. Everything else is an object, including arrays and functions. Primitives are immutable and compared by value; objects are compared by reference, so two identical-looking objects are not equal. typeof null returns "object", a long-standing quirk, so check for null with === null.
What the interviewer is checking: Value versus reference, and whether you know the classic quirks.
2. What is the difference between == and ===?
Model answer: === compares without type conversion: different types are never equal. == converts types first by a set of rules, which gives results like 0 == '' and '1' == 1 being true. One case is useful: x == null is true for both null and undefined. Neither handles NaN, which is not equal to itself, so use Number.isNaN(x); Object.is is a third comparison that treats NaN as equal to NaN and 0 and -0 as different.
What the interviewer is checking: Coercion awareness and a clear default (===).
3. What is hoisting, and how do function declarations and function expressions differ?
Model answer: Declarations are registered when a scope is set up, before its code runs. A function declaration is hoisted with its body, so you can call it above the line where it is written. A function expression assigned to a variable follows the variable: with var the name exists but is undefined, so calling it early throws a TypeError, and with let or const touching it early throws a ReferenceError because of the temporal dead zone. Classes behave like let.
What the interviewer is checking: That you can explain the errors you would get, not just the word "hoisting".
4. How is the value of this decided?
Model answer: By how a function is called, not where it is written. Called as obj.method(), this is obj. Called as a plain function, it is undefined in strict mode and modules, or the global object in sloppy scripts. With new it is the newly created object, and call, apply and bind set it explicitly. Arrow functions have no this of their own and use the one from the surrounding scope, which is why they work well as callbacks inside methods.
What the interviewer is checking: Call-site reasoning, and the common bug of passing obj.method as a callback and losing this.
5. Which values are falsy, and what is the difference between || and ???
Model answer: The falsy values are false, 0, -0, 0n, '', null, undefined and NaN; everything else is truthy, including '0', [] and {}. a || b returns b whenever a is falsy, so count || 10 replaces a real count of 0. a ?? b returns b only when a is null or undefined, which is usually what a default means.
What the interviewer is checking: Whether you would ship the || default bug.
6. What is event delegation, and why use it?
Model answer: Instead of a listener on every child, you add one listener to a common parent and use the fact that most events bubble up. In the handler, event.target.closest() finds the element that was actually clicked. It uses less memory for long lists and works for children added later without re-binding. Events that do not bubble, such as focus, need focusin or a capture listener instead.
list.addEventListener('click', (event) => {
const button = event.target.closest('button[data-id]');
if (!button || !list.contains(button)) return;
removeItem(button.dataset.id);
});
What the interviewer is checking: Understanding of bubbling and practical DOM work without a framework.
7. What do map, filter, reduce and forEach return?
Model answer: map returns a new array of the same length with each element transformed. filter returns a new array with only the elements for which the callback returned a truthy value. reduce folds the array into a single value of any type, starting from the initial value you pass. forEach returns undefined and is only for side effects. None of them changes the original array unless the callback does, and none of them waits for async callbacks.
What the interviewer is checking: Fluency with the everyday tools, and the async callback trap.
Mid-level JavaScript questions
Mid-level questions move to asynchronous code, objects and modules: the areas where production bugs come from.
8. What does this code print, and why?
Model answer: It prints 1, 4, 6, 3, 5, 2. The synchronous code runs first: 1, then the async function runs up to its first await and prints 4, then 6. The .then callback and the rest of the async function after await were queued as microtasks, in that order, so 3 and then 5 run as soon as the script finishes. The timeout is a task, so 2 comes last, even with a delay of 0.
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
(async () => {
console.log('4');
await null;
console.log('5');
})();
console.log('6');
What the interviewer is checking: That you know an async function runs synchronously until its first await.
9. How do you use a closure to keep state private?
Model answer: A function returned from another function keeps access to the outer function's variables, even after the outer one has returned. Nothing outside can reach those variables except through the functions you return, so they behave like private fields. The same pattern powers memoization caches, once helpers and factories. Classes now have real private fields with #, but closures are still common in functional code and hooks.
function makeCounter() {
let count = 0;
return {
increment: () => ++count,
current: () => count,
};
}
const counter = makeCounter();
counter.increment();
counter.current(); // 1
What the interviewer is checking: That you can use closures on purpose, not only recognize them in a bug.
10. Explain prototypal inheritance and how class relates to it.
Model answer: Every object has an internal link to a prototype object. When you read a property the object does not have, JavaScript looks it up along that chain until it finds it or reaches null. class is syntax over the same mechanism: methods go on Constructor.prototype, and extends links one prototype to another. That is why all instances share one copy of each method, and why adding a method to a prototype affects existing instances.
What the interviewer is checking: The model under the syntax, which matters when debugging or reading older code.
11. What is the difference between Promise.all, allSettled, race and any?
Model answer: Promise.all resolves with all results in order, or rejects as soon as one input rejects. Promise.allSettled always waits for every input and gives you an array of {status, value} or {status, reason} objects. Promise.race settles like the first input to settle, success or failure, which is the usual way to add a timeout. Promise.any resolves with the first success and rejects with an AggregateError only if all of them fail.
What the interviewer is checking: Choosing the right combinator for partial failure, which comes up in real UIs.
12. How do you run several async requests in parallel instead of one after another?
Model answer: An await inside a loop waits for each request before starting the next, so the total time is the sum of all of them. Start all the promises first and await them together with Promise.all, and the total is roughly the slowest one. If one failure should not lose the other results, use Promise.allSettled. For hundreds of requests, limit how many run at once so you do not overload the server or the browser's connection pool.
// One after another: each request waits for the previous one
const results = [];
for (const id of ids) results.push(await getUser(id));
// In parallel: start them all, then wait for all of them
const users = await Promise.all(ids.map((id) => getUser(id)));
What the interviewer is checking: Whether you notice accidental sequential awaits, a common performance bug.
13. What is the difference between a shallow and a deep copy?
Model answer: A shallow copy, made with spread ({ ...obj }, [...arr]) or Object.assign, copies the top level only; nested objects are still shared, so changing one changes the original. structuredClone(obj) makes a deep copy and handles dates, maps, sets and circular references, but throws on functions and DOM nodes. JSON.parse(JSON.stringify(obj)) is the old trick and silently turns dates into strings and drops properties whose value is undefined or a function.
What the interviewer is checking: That you know what each method loses, and can name the modern built-in.
14. Implement debounce, and explain how it differs from throttle.
Model answer: Debounce waits until calls have stopped for wait milliseconds and then runs once with the last arguments, which suits search-as-you-type. Throttle runs at most once per interval while calls keep coming, which suits scroll or resize handlers. In this version each call clears the previous timer. The returned function is a regular function so it passes its own this through to fn.
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
What the interviewer is checking: Closures and timers used together, and choosing between the two patterns.
15. How do ES modules differ from CommonJS?
Model answer: ES modules use import and export, which are static: tools can see the dependency graph without running the code, which is what makes tree shaking possible. Imports are live, read-only bindings to the exported variable, modules are always in strict mode, and they can use top-level await. CommonJS uses require() and module.exports, loads synchronously at runtime, and a destructured value is a copy taken at that moment. Node.js supports both; browsers run ES modules natively.
What the interviewer is checking: Module basics you need to debug bundling and interop problems.
Senior JavaScript questions
Senior questions are about the runtime: memory, the main thread and how a large codebase fails in production.
16. How does garbage collection work, and how would you find a memory leak in a web app?
Model answer: Engines collect objects that can no longer be reached from roots such as globals and the current call stack, mainly with mark-and-sweep. A leak is therefore something still reachable that you no longer need: a listener never removed, an interval never cleared, a cache or Map that only grows, or a detached DOM node held by a closure. To find one, I take heap snapshots in Chrome DevTools before and after repeating an action several times, compare them, and follow the retainers of what grew. Then I fix the reference and check again.
What the interviewer is checking: A real debugging method, not just "use WeakMap".
17. How do you keep the main thread responsive during heavy work?
Model answer: The browser can only handle input and paint between tasks, so any task longer than about 50 milliseconds, which the browser reports as a long task, delays the next interaction. Split the work into chunks and yield between them, with setTimeout, or scheduler.yield() where the browser supports it. Move pure computation such as parsing or image processing into a Web Worker. A long chain of microtasks does not help, because the browser does not render until the microtask queue is empty.
What the interviewer is checking: Event-loop knowledge applied to real responsiveness, the thing INP measures.
18. What is a WeakMap, and when would you use one?
Model answer: A WeakMap uses objects as keys and holds them weakly: if nothing else references a key object, it can be garbage-collected and its entry disappears. For that reason it is not iterable and has no size. It is the right tool for attaching data to objects you do not own, such as metadata on DOM nodes or a cache of results computed per object, without causing a memory leak.
What the interviewer is checking: Precise semantics and a real use case.
19. How does for...of work, and how would you make your own object iterable?
Model answer: for...of calls the object's Symbol.iterator method to get an iterator, then calls its next() method until it returns { done: true }. Arrays, strings, maps and sets have one built in; plain objects do not. The simplest way to add one is a generator method, since generators produce iterators. The same protocol drives spread, destructuring and Array.from.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) yield i;
}
}
[...new Range(1, 4)]; // [1, 2, 3]
What the interviewer is checking: Understanding of a core protocol rather than memorized array methods.
20. How would you set up error handling and reporting for a large frontend codebase?
Model answer: I would catch errors at three levels. Locally, try/catch around code that can fail for expected reasons, with a useful message to the user. At the UI level, error boundaries or their equivalent, so one broken widget does not blank the page. Globally, listeners for error and unhandledrejection that send reports, with uploaded source maps, release versions and grouping, to a service such as Sentry. Then alerts on new error groups after each release, and an owner for each one.
What the interviewer is checking: Thinking in layers and in operations, not just syntax.
JavaScript coding round
Common live tasks are re-implementing a built-in or writing a small utility. Ask about edge cases before you start: empty input, errors, very large input.
21. Implement Promise.all.
Model answer: Return a new promise. Wrap each input in Promise.resolve so plain values work too, store each result at its own index so the order matches the input, and resolve once the counter of pending items reaches zero. Pass reject straight through, so the first failure rejects the whole thing. An empty input resolves immediately with an empty array, like the built-in.
function promiseAll(items) {
return new Promise((resolve, reject) => {
const results = [];
let pending = 0;
for (const item of items) {
const index = pending++;
Promise.resolve(item).then((value) => {
results[index] = value;
if (--pending === 0) resolve(results);
}, reject);
}
if (pending === 0) resolve(results);
});
}
What the interviewer is checking: Order of results, the empty case, and that then callbacks always run asynchronously.
22. Flatten a nested array without using flat().
Model answer: Walk the array; when an element is itself an array, flatten it recursively and add its items, otherwise add the element. This handles any depth. Mention that the built-in is arr.flat(Infinity), and that recursion can overflow the call stack for extremely deep nesting, which an explicit stack fixes. Spreading a very large child into push can also hit argument limits, so a loop is safer at scale.
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) out.push(...flatten(item));
else out.push(item);
}
return out;
}
flatten([1, [2, [3, [4]]], 5]); // [1, 2, 3, 4, 5]
What the interviewer is checking: Clean recursion and whether you raise the limits yourself.
How to practice
Run each code sample, change one line and predict the new output before you run it again. Then answer the conceptual questions out loud without looking. Rehearse out loud with the free voice mock interviewer at interview.flexq.app: paste the job description, add your résumé if you like, and answer by voice (typing works too). It follows up where an answer is thin and ends with a scored report that quotes your answers back. Three mock interviews are free with an email sign-up, no card.
During the real interview, the FlexQ interview copilot can show short cues on the interviewer's questions, grounded in your résumé and the job post, and you answer in your own words. Follow the rules of the company you're interviewing with.
Practice a free mock interview
Paste a JavaScript or frontend job description and the mock interviewer asks questions like these and follows up on your reasoning. Three mock interviews are free with an email sign-up, no card.
For live interviews: the FlexQ interview copilot for Mac or Windows, 30 free live minutes.
On the real call
FlexQ also has a live copilot for macOS and Windows. Add your résumé and the job description, and when a question like these lands it shows a short cue from your own experience, so you answer in your own words. Your first 30 live minutes are free. Get FlexQ.
FAQ
What JavaScript topics come up most in interviews?
Closures, this, promises and async/await, the event loop, equality and coercion, and array methods. Frontend roles add DOM events; senior roles add memory and performance.
Are "what does this print" questions still common?
Yes, especially about the event loop, this and closures. Practice by predicting the output of small snippets before running them, and say your reasoning out loud.
Do I need to know TypeScript for a JavaScript interview?
Many frontend jobs use TypeScript, so expect at least a few questions about it. The JavaScript runtime questions still come first, because TypeScript types disappear at runtime. The TypeScript questions cover that side.
Should I use an older or newer syntax in a live coding round?
Modern syntax (const, arrow functions, async/await, optional chaining) is expected. Ask if the editor or environment has limits, and say so if you use a newer built-in such as structuredClone.
How do I practice JavaScript questions for an interview?
Run every snippet you study, then explain it out loud as if to an interviewer. Write the common utilities (debounce, Promise.all, flatten, deep equal) from an empty file with a timer.
Related
Frontend topics: React · TypeScript · Webpack, Vite and tooling · Frontend system design · Frontend developer
More: Software engineer questions · System design interview questions · "Tell me about yourself" · Practice out loud · All interview questions