JavaScript interview questions and answers for developers
JavaScript interview questions test whether you can predict what code does: scope and closures, the this keyword, type coercion, prototypes, and the order in which promises, timers and async functions run. Expect a mix of concept questions, output-prediction snippets and a small implementation such as debounce or Promise.all. Answer by naming the rule that decides the output, not by guessing the output.
By Evin JohnPublished 8 min read
How JavaScript is tested in developer interviews
Frontend, full stack and Node.js roles all include a JavaScript round, and so do many general software engineering loops when the candidate picks JavaScript as their language. The format is usually a shared editor without a runner, which is why output prediction is popular: it shows whether your mental model of the language is accurate when nothing executes the code for you.
- Language quizRapid questions on scope, equality, types and
this. Short, precise answers win; a one-line example helps. - What does this print?Five to ten lines mixing closures, timers and promises. Walk through it line by line and say which queue each callback joins.
- Implement a utilityDebounce, throttle, deep clone, an event emitter, a curry helper, or your own Promise.all. Edge cases are the point.
- Practical problemFetch and combine data from two APIs, handle errors and cancellation, or refactor callback code to async/await.
JavaScript fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the primitive types? | Type system | string, number, bigint, boolean, undefined, symbol and null. Everything else is an object, including arrays and functions. typeof null returning "object" is a historic bug kept for compatibility. |
| How do var, let and const differ? | Scope and hoisting | var is function-scoped and initialized to undefined when hoisted. let and const are block-scoped and sit in the temporal dead zone until their declaration runs. const stops reassignment, not mutation. |
What does == do that === does not? | Equality and coercion | Loose equality converts types first. Know the safe exception: x == null matches both null and undefined. Otherwise default to strict equality. |
Why is 0.1 + 0.2 === 0.3 false? | Floating point | Numbers are IEEE 754 doubles, so some decimals cannot be stored exactly. Compare with a tolerance, or keep money in integer cents or BigInt. |
| What is NaN and how do you test for it? | Special values | NaN is not equal to itself. Use Number.isNaN. [NaN].includes(NaN) is true while indexOf returns -1, because includes uses SameValueZero. |
| Function declaration versus function expression? | Hoisting | Declarations are hoisted with their body. A function expression assigned to var is hoisted only as undefined. |
| What does strict mode change? | Language modes | Assigning to an undeclared variable throws, this in a plain call is undefined instead of the global object, and some silent failures become errors. Modules and classes are always strict. |
| Spread copy versus deep copy? | References | Spread and Object.assign copy one level. Nested objects stay shared. structuredClone copies deeply, including Dates and Maps, but throws on functions. |
| What is the difference between null and undefined? | Absent values | undefined means not assigned; null is an intentional empty value. JSON drops keys whose value is undefined. |
| Map versus plain object? | Collections | Map keeps insertion order for any key type, has a size, and avoids prototype keys. Objects suit fixed records and JSON. |
console.log([] + []); // ""
console.log([] + {}); // "[object Object]"
console.log(1 + "2"); // "12"
console.log("5" - 2); // 3
console.log("3" * "4"); // 12
console.log(true + 1); // 2
console.log(null == undefined); // true
console.log(null == 0); // false
console.log(null >= 0); // true
console.log([10, 1, 2].sort()); // [1, 10, 2]The last three lines are the ones to explain. null == 0 is false because loose equality treats null specially, while >= converts null to 0. sort() without a comparator compares strings, so pass (a, b) => a - b for numbers.
Closures, scope and this
- What is a closure, in one sentence? A function bundled with the variables of the scope it was created in, which stay alive as long as the function does.
- Give a practical use of a closure. Private state in a factory such as a counter, memoizing a function, or binding configuration into a handler.
- What decides the value of this inside a function? By the call site: a method call uses the object before the dot,
newuses the new object,call,applyandbindset it explicitly, and a plain call gives undefined in strict code. Arrow functions have no ownthisand use the enclosing one. - Why does a method lose its this when passed as a callback? Because the callback is later called as a plain function. Fix with an arrow wrapper or
bind. - How does prototypal inheritance work? Property lookup walks the prototype chain until it finds the key or reaches null. Classes are syntax over the same mechanism.
- What do private class fields such as #count give you that closures also give you? Real privacy enforced by the language, per instance, with clearer syntax than a factory function.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var", i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let", j), 0);
}
// var 3, var 3, var 3, then let 0, let 1, let 2
// var shares one binding across the loop; let creates a new one per iteration.const user = {
name: "Ada",
greet() { return `hi ${this.name}`; },
later() { return [1].map(() => this.name); },
};
const greet = user.greet;
console.log(user.greet()); // "hi Ada"
console.log(user.later()); // ["Ada"] (the arrow uses later's this)
console.log(greet()); // TypeError: this is undefined- A script logs typeof decl and typeof expr, and only afterwards declares a function decl and a var expr holding a function expression. What prints? "function undefined". The declaration is hoisted with its body; the var is hoisted empty.
- What does [1, 2, 3].map(parseInt) return?
[1, NaN, NaN], because map passes the index as parseInt's radix argument. - What happens if you read a let variable before its line? A ReferenceError from the temporal dead zone, not undefined.
Async JavaScript and the event loop
Async ordering is the most common output-prediction topic. The rule: run all synchronous code, then drain the whole microtask queue (promise reactions, queueMicrotask, the code after an await), then take one task such as a timer callback, and repeat.
async function a() {
console.log("a1");
await b();
console.log("a2");
}
async function b() {
console.log("b");
}
console.log("s");
setTimeout(() => console.log("t"), 0);
a();
new Promise((resolve) => {
console.log("p");
resolve();
}).then(() => console.log("then"));
console.log("e");Explain it in order. "s" is synchronous. The timer is queued as a task. Calling a() runs synchronously up to the await, printing "a1" and "b". The promise executor runs immediately, printing "p", and "e" is synchronous. Then the microtasks run in the order they were queued, the rest of a and then the then callback, and finally the timer.
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Promise.all, allSettled, race and any: when do you use each? | Combinators | all fails fast on the first rejection; allSettled always waits and reports each result; race settles with the first to settle; any resolves with the first success and rejects only if all fail. |
| How do you run five requests in parallel with async/await? | Concurrency | Start them first and await Promise.all, rather than awaiting inside a for loop, which runs them one after another. |
| What happens to an error thrown inside a then callback? | Error propagation | It rejects the promise returned by then and skips to the next catch. An unhandled rejection is reported by the runtime and can end a Node.js process. |
| How do you cancel a fetch? | Cancellation | Pass an AbortController's signal and call abort. The promise rejects with an AbortError that you handle separately from real failures. |
| How do you limit concurrency to three requests at a time? | Task pools | Keep a queue and start a new request when one finishes, or use a small worker pool of async loops pulling from a shared iterator. |
| Why can a forEach with an async callback finish before the work? | Async iteration | forEach ignores returned promises. Use for...of with await for sequence or map plus Promise.all for parallel. |
What does await do to code after it? | Async functions | Everything after it runs later as a microtask, even if the awaited value is not a promise. |
Implementation questions
These test whether you can turn your understanding into working code. Say the edge cases first: an empty input, a rejected promise, the right this and arguments, and what the function returns.
function promiseAll(items) {
return new Promise((resolve, reject) => {
const results = new Array(items.length);
let remaining = items.length;
if (remaining === 0) return resolve(results);
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
remaining -= 1;
if (remaining === 0) resolve(results);
}, reject);
});
});
}function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}- Implement throttle and explain how it differs from debounce. Throttle runs at most once per interval during a burst; debounce waits for quiet. Mention leading and trailing calls.
- Write a deep equal function. Handle primitives, arrays, plain objects and NaN, and say what you skip (cycles, Maps, Dates) unless asked.
- Build a tiny event emitter with on, off and emit. Store listeners per event in a Map of arrays, copy the array before emitting so a listener that unsubscribes does not break the loop.
- Write curry for a function of known arity. Collect arguments until
args.length >= fn.length, then call. - Flatten a nested array without Array.prototype.flat. Recursion or an explicit stack. Ask whether the depth is limited.
- Memoize a one-argument function. A Map keyed by the argument. Discuss unbounded growth and when a WeakMap helps.
Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| Memory grows every time a user opens and closes a panel. | Leaks | Event listeners or intervals never removed, closures holding large objects, detached DOM nodes. Use a heap snapshot comparison to find what is retained. |
| The page freezes while a large file is parsed. | Main thread | Long synchronous work blocks rendering and input. Move it to a Web Worker or split it into chunks. |
| A search box shows results for an older query. | Race conditions | Responses arrive out of order. Abort the previous request or ignore responses whose query no longer matches. |
| Prices show 19.999999 in the cart. | Number precision | Floating point. Store cents as integers and format at display time with Intl.NumberFormat. |
| ES modules versus CommonJS in one codebase? | Module systems | Static import and export with live bindings versus require at runtime. Interop rules and file extensions matter in Node.js. |
| When would you choose TypeScript over plain JavaScript? | Judgment | Shared code, refactors and API contracts benefit most; covered in depth in the TypeScript interview questions. |
Fictional example
- A closure is a function that remembers the variables around it when it was created. In our analytics script, every tracked button got a click handler made by a small factory that captured the button's name and a counter, so each handler kept its own count without any global state. The flip side bit us once: a handler captured a large response object it only needed one field from, and since the handler lived as long as the page, so did the object. We fixed it by copying the one field into a local variable before creating the handler. So I think of closures as a tool for private state that also decides what stays in memory.
Two-week JavaScript practice plan
- Days 1 to 3: types, coercion, scope and hoisting. For each rule, write a three-line snippet that proves it and predict the output before you run it.
- Days 4 to 6: closures,
thisin every call style, prototypes and classes. Explain each aloud in under a minute. - Days 7 to 9: the event loop. Write ten ordering puzzles mixing timers, promises and await, and check yourself.
- Days 10 to 12: implement debounce, throttle, Promise.all, an event emitter and deep equal from a blank file, timed.
- Days 13 and 14: a practical task that fetches, combines and caches data with errors and cancellation, then review it as if it were someone else's pull request.
If the job is React-heavy, continue with React interview questions; for server roles, Node.js interview questions builds on the event loop section here. The broader role view is in frontend developer interview questions.
Predicting output out loud is a skill you can rehearse. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of your mock JavaScript round so you can see where an explanation of the event loop wandered. In practice it can read a snippet from a screenshot, give a coding hint, or write an approach, and with Pro or the free trial it can draw on the résumé and job description you add. Your sessions and notes are kept for later review.
Questions people ask
What JavaScript questions are asked in interviews?
Expect scope and hoisting, equality and coercion, closures, this binding, prototypes, and the event loop with promises and async/await. Many rounds add output-prediction snippets and a small implementation such as debounce or Promise.all.
How do I answer JavaScript output questions?
Go line by line, run the synchronous code first, then name which queue each callback joins: microtasks for promise reactions and code after await, tasks for timers. State the rule before the output.
What JavaScript topics matter most for experienced developers?
Async control flow and error handling, memory leaks, race conditions in the UI, module systems, and the reasoning behind your own utilities and abstractions.
Do JavaScript developer interviews include coding?
Usually. Common tasks are implementing debounce or throttle, a promise helper, an event emitter or deep equality, or fetching and combining data with proper error handling.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
