165 JavaScript interview questions with answers
165 JavaScript interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
All JavaScript interview questions
What is the difference between var, let, and const?
What are the primitive data types in JavaScript?
What is Symbol in JavaScript and what is it used for?
What is the difference between == and ===?
What is type coercion in JavaScript?
What are truthy and falsy values in JavaScript?
What is NaN? Why is NaN !== NaN?
What is hoisting in JavaScript?
What is the Temporal Dead Zone (TDZ)?
How does the scope chain work in JavaScript?
What is a closure? Give a practical example.
How can closures cause memory leaks?
What is the classic closure-in-loop problem with var?
What is the difference between function declarations and function expressions in terms of hoisting?
Why does var in global scope create a property on the window object?
What is a stale closure and how do you prevent it?
What is the difference between function declarations, function expressions, and arrow functions?
What is a callback function? Why does JavaScript use callbacks?
What is a higher-order function? Give an example.
What is an IIFE (Immediately Invoked Function Expression) and what is it used for?
What is a pure function? Why are pure functions important?
What is currying? Give an example and a real-world use case.
What is memoization? How do you implement a simple memoize function?
What are rest parameters (...args)? How do they differ from the arguments object?
What is function composition?
What is a generator function? When should you use one?
What is callback hell? What are solutions to avoid it?
What are the rules for determining the value of this in JavaScript?
How does strict mode affect this?
What is the difference between call(), apply(), and bind()?
Why is an arrow function unsuitable as an object method?
How do constructor functions and the new keyword work?
What is this in a JavaScript class?
What is the prototype chain in JavaScript?
What is the difference between __proto__ and prototype?
How does Object.create() work?
How does the instanceof operator work?
How do hasOwnProperty() and the in operator differ?
What is prototype pollution and how do you prevent it?
What is destructuring assignment? Give examples with arrays and objects.
How do the spread operator (...) and rest parameters (...) differ?
What are template literals? What features do they have?
What are ES6 classes? How do they differ from function constructors?
What are private class fields (#)?
What is the difference between for...of and for...in?
What is the difference between Map and WeakMap?
What are Set and WeakSet?
What are ES modules (import/export)?
What are Proxy and Reflect in ES6?
What are Symbol.iterator and the iterable protocol?
How do Object.assign() and the spread operator differ when copying objects?
What are logical assignment operators (&&=, ||=, ??=)?
What is the difference between Array.from() and the spread operator when converting array-likes?
What are the new String methods in ES6+ like padStart, padEnd, includes, startsWith?
What is the at() method for Array and String?
What is a Promise? What states does it have?
How do .then(), .catch(), and .finally() work?
How does the JavaScript event loop work?
What is the difference between microtasks and macrotasks?
What is async/await? Why is it easier than Promise chains?
How do you handle errors in async/await?
What is async iteration (for await...of)?
Does setTimeout(fn, 0) actually run immediately?
How do you use AbortController to cancel a fetch request?
What is a race condition in async JavaScript and how do you handle it?
How do you use async/await with parallel execution?
What is an unhandled promise rejection? How do you handle it?
What are requestAnimationFrame and requestIdleCallback in JavaScript task scheduling?
How do long tasks relate to JavaScript performance and the event loop?
What is the DOM? How does JavaScript interact with it?
What is the difference between getElementById, querySelector, and querySelectorAll?
What is event delegation? Why is it efficient?
What is the difference between preventDefault() and stopPropagation()?
What is the Fetch API? How does it differ from XMLHttpRequest?
What are Web Workers? When should you use them?
What is the IntersectionObserver API and what is it used for?
What is MutationObserver?
How do cookies, localStorage, and sessionStorage differ in terms of security and usage?
What are custom events in JavaScript?
What is requestAnimationFrame and why should you use it instead of setTimeout for animations?
What are Service Workers?
What is the difference between textContent, innerText, and innerHTML?
What is IndexedDB? When should you use it instead of localStorage?
Implement a debounce function from scratch (without lodash).
Implement a throttle function from scratch.
Implement a deep clone function (without using structuredClone).
Flatten a nested array (without using Array.flat).
Implement Promise.all from scratch.
Implement a simple EventEmitter class.
Write a useLocalStorage hook in React.
Implement an infinite scroll hook.
Implement a general-purpose curry function.
Implement a simple React context store (mini Redux).
Write a retry function with exponential backoff.
Implement a simple virtual list (render only visible items).
Write a function to deep-compare two objects for equality.
Implement a memoize function for expensive computations.
Implement a simple pub/sub system for micro-frontends.
Write a middleware pipeline pattern (like Express).
FizzBuzz coding challenge. Write the code, optimize it, and handle edge cases.
Implement a simple LRU cache. Explain the HashMap + LinkedList data structure.
Array method efficiency. How do map, forEach, and reduce compare in performance?
What is a memory leak in JavaScript and what are the common causes?
What are Object.groupBy() and Map.groupBy() (ES2024), and when do you pick one over the other?
What problem does Promise.withResolvers() (ES2024) solve compared to new Promise()?
How does Array.fromAsync() (ES2024) differ from Array.from() and Promise.all()?
What are the new ES2025 Set methods (union, intersection, difference, isSubsetOf...) and what's the argument gotcha?
What is structuredClone() and how does it differ from JSON.parse(JSON.stringify())?
What are WeakRef and FinalizationRegistry, and why do the docs advise restraint?
What are ES2025 iterator helpers (map, filter, take, drop), and what's the laziness advantage over array methods?
What do Array.prototype.at(), findLast(), and findLastIndex() do that the old way struggled with?
What is the RegExp /v (unicodeSets) flag in ES2024, and how does it improve on /u?
What is top-level await in ES modules, and how does it affect module load order?
What are generators and iterators in JavaScript?
What order does this code print? Explain.
```js
setTimeout(() => console.log('timeout'), 0)
setImmediate(() => console.log('immediate'))
Promise.resolve().then(() => console.log('promise'))
process.nextTick(() => console.log('nextTick'))
console.log('sync')
```
Why is the order of `setTimeout(fn, 0)` vs `setImmediate(fn)` non-deterministic in the main module, yet `setImmediate` always runs first inside an I/O callback?
How do you measure whether the event loop is blocked in production? Which metric belongs on the dashboard?
Why can recursion via `process.nextTick()` kill an application while recursion via `setImmediate()` does not?
What do `[] + {}` and `{} + []` evaluate to? Explain why.
Why is `0.1 + 0.2 !== 0.3`? How do you handle money in a real system?
What goes wrong when you use a plain object as a cache keyed by objects? When must you use `Map`?
How does `delete obj.x` differ from `obj.x = undefined`?
Does `Object.freeze` make an object fully immutable? How do you freeze deeply?
Why does `const fn = obj.method; fn()` lose `this`? What are the fixes?
What bug does `const limit = input.limit || 20` cause? How is `??` different from `||`?
The API returns `{ name: null }` yet `const { name = 'Guest' } = user` still gives `null`. Why? And how do you rename while destructuring?
What does `for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))` print? What changes with `let`?
Are `let`/`const`/`class` hoisted? What is the TDZ?
Do spread `{...obj}` and `Object.assign` copy deeply? What do you use for a deep copy?
How does `__proto__` differ from `prototype`? Do `class` and `Object.create` build the same prototype chain?
How do `call`, `apply`, and `bind` differ? If you `bind` twice, which `this` wins?
How do you make your own object work with `for...of` and spread? How does the iterator protocol work?
What extra control does `Object.defineProperty` give over a plain assignment? Why does Proxy supersede it?
JavaScript has a garbage collector, so how do memory leaks still happen? Name common sources on the web.
What order does the following code print, and why?
Why does an `async function` always return a Promise? What happens if you call it without `await`?
Why does `array.forEach(async (item) => await save(item))` not wait? How do you fix it?
Why does `try/catch` fail to catch an error thrown inside a `setTimeout` callback?
A dashboard calls 5 independent APIs and one is slow or failing. Do you pick `Promise.all`, `allSettled`, `race`, or `any`? Why?
When must API calls be sequential (`for await`) and when should they be parallel (`Promise.all`)? What does getting it wrong cost?
`fetch` has no default timeout. How do you add one and cancel the request?
How do you implement client-side retry with exponential backoff? Which requests may be retried?
In a search box, results for an older query arrive late and overwrite the newer results. How do you fix it?
How is debouncing an **async** function different from a sync one? Where are the traps?
How do `return await promise` and `return promise` differ? When is `return await` mandatory?
You must upload 500 files but only 5 requests may run at a time. How do you implement that?
What happens when a Promise rejects with no `.catch()`? Why does `Promise.all` make this easy to hit?
Within one event-loop turn, what is the order of microtasks, `requestAnimationFrame`, and `setTimeout`? Where does rendering fit?
What problem do async generators and `for await...of` solve? Show a paginated API example.
Why does `async/await` not make code run in parallel? When is a Web Worker actually required?
What steps does the browser take from HTML to pixels on screen (the critical rendering path)?
How do cookies, localStorage, sessionStorage and IndexedDB differ? When do you pick each?
How do DOM events propagate (capturing vs bubbling)? What is event delegation?
What do the `HttpOnly`, `Secure` and `SameSite` cookie attributes do? How would you configure a session cookie?
What are the stages of the service worker lifecycle? Why do users still see the old build after a deploy?
How do you implement infinite scroll with `IntersectionObserver`? What do `root`, `rootMargin` and `threshold` do, and what are the pitfalls?
What caching strategies exist in a service worker? Which one fits HTML, hashed assets, and API calls?
How do you synchronize state across tabs (e.g. logging out in one tab logs out the others)?
What is a `Partitioned` cookie (CHIPS)? How does the third-party cookie clampdown affect SSO and embedded widgets?
How would you design a login flow that stores tokens and refreshes them on expiry?
How do you build an image upload with preview and client-side compression?
Dark mode flashes white for a moment on load (FOUC) — why, and how do you fix it?
How do you correctly display VND amounts and dates/times for Vietnam?
How should the frontend handle the user losing network connectivity mid-session?
Your page renders user-submitted comments — how do you prevent XSS?