JavaScript Interview Questions (60+ Deep Dive Q&A)
1. Core Engine & Internals (V8)
1. The Event Loop (Visualized)
1. The Event Loop (Visualized)
- Call Stack: Sync code execution.
- Web APIs: Browser threads (Timer, Fetch, DOM).
- Callback Queue (Macrotask):
setTimeout,setInterval. - Microtask Queue:
Promise.then,MutationObserver. Higher Priority.
2. Execution Context & Hoisting
2. Execution Context & Hoisting
- Creation Phase: Scanner runs.
varinitialized toundefined.functiondeclarations stored fully in memory (Hoisting).let/constenter Temporal Dead Zone (TDZ). - Execution Phase: Code runs line by line.
3. Closure Scope Chain
3. Closure Scope Chain
4. `this` Binding Rules
4. `this` Binding Rules
- New Binding:
new Constructor().this= new object. - Explicit Binding:
call,apply,bind. - Implicit Binding:
obj.method().this=obj. - Default:
windoworundefined(strict mode). Arrow Functions: Lexicalthis. They inheritthisfrom the outer scope execution context.
5. Prototype Chain vs Class
5. Prototype Chain vs Class
class is syntax sugar over Prototypal Inheritance.- Prototype: Every object has
__proto__pointing to another object (or null). - Lookup: If property not in
obj, checkobj.__proto__, thenobj.__proto__.__proto__.
6. Garbage Collection (Mark and Sweep)
6. Garbage Collection (Mark and Sweep)
- Roots: Global execution context, window.
- Mark: Traverse from roots. Mark reachable objects.
- Sweep: Delete unreachable (unmarked) objects. Leak Types:
- Accidental Globals (
window.x = 5). - Forgotten Timers.
- Closures holding huge objects.
- Detached DOM nodes.
7. V8 Hidden Classes (Optimization)
7. V8 Hidden Classes (Optimization)
8. JIT Compilation (Hot & Cold)
8. JIT Compilation (Hot & Cold)
- Interpreter (Ignition): Runs bytecode fast. Profiles code (“Cold”).
- Compiler (TurboFan): Takes “Hot” (frequently used) code, assumes types (e.g., “always integer”), and compiles to Optimized Machine Code.
- De-opt: If type assumption fails (e.g., passed a string), JIT bails out to Interpreter.
- Keep function arguments consistent types
- Avoid changing object shapes
- Don’t mix integers and floats
- Avoid
argumentsobject (use rest parameters)
9. Strict Mode (`'use strict'`)
9. Strict Mode (`'use strict'`)
- Prevents accidental globals.
thisisundefinedin standalone functions (notwindow).- Disables
with. - Throws error on assignment to read-only props.
10. WeakMap vs Map
10. WeakMap vs Map
| Feature | Map | WeakMap |
|---|---|---|
| Keys | Any type | Objects only |
| Iteration | Iterable | Not iterable |
| GC | Prevents GC of keys | Allows GC of keys |
| Use | Caches, dictionaries | DOM Node metadata |
2. Async Patterns
11. Promise Internals (Polyfill)
11. Promise Internals (Polyfill)
then (Observer pattern).
Microtask: Callbacks are executed asynchronously via Microtask Queue.12. Async/Await (Generator + Promise)
12. Async/Await (Generator + Promise)
try/catch is sync-style.
Parallelism:- Bad:
await a(); await b();(Sequential). - Good:
await Promise.all([a(), b()])(Parallel).
13. `Promise.all` vs `allSettled` vs `race`
13. `Promise.all` vs `allSettled` vs `race`
- all: Fails fast. If one rejects, implementation throws immediately.
- allSettled: Waits for ALL. Returns
{ status: 'fulfilled' | 'rejected' }. - race: Returns first to settle (resolve OR reject).
- any: Returns first to resolve (ignores rejections unless all fail).
14. AbortController (Cancelling Fetch)
14. AbortController (Cancelling Fetch)
15. Microtask vs Macrotask Queue (Quiz)
15. Microtask vs Macrotask Queue (Quiz)
1, 4, 3, 2.
Sync -> Sync -> Microtask -> Macrotask.3. DOM & Browser APIs
16. Bubbling vs Capturing (Event Delegation)
16. Bubbling vs Capturing (Event Delegation)
- Capture Phase: Window -> Target.
- Target Phase: At element.
- Bubble Phase: Target -> Window.
Delegation: Attach listener to Parent. Use
e.targetto find Child. Saves memory (1 listener vs 1000). Stop:e.stopPropagation()stops bubbling.
17. Debounce vs Throttle
17. Debounce vs Throttle
- Debounce: “Group calls”. Run only after X ms of silence. (Search Box).
- Throttle: “Rate limit”. Run at most once every X ms. (Scroll event).
18. Critical Rendering Path
18. Critical Rendering Path
- HTML -> DOM Tree.
- CSS -> CSSOM Tree.
- DOM + CSSOM -> Render Tree.
- Reflow (Layout): Calculate geometry (width, height).
- Repaint: Fill pixels (color, shadow).
- Composite: Layer assembly (GPU). Reflow is expensive.
19. Efficient DOM Manipulation (DocumentFragment)
19. Efficient DOM Manipulation (DocumentFragment)
DocumentFragment (Virtual DOM node), then append Fragment once. display: none also works.20. LocalStorage vs SessionStorage vs Cookies
20. LocalStorage vs SessionStorage vs Cookies
21. IntersectionObserver (Infinite Scroll)
21. IntersectionObserver (Infinite Scroll)
scroll event listeners.22. Shadow DOM
22. Shadow DOM
element.attachShadow({ mode: 'open' }).23. Web Workers
23. Web Workers
postMessage.
Limitations: No DOM access. No window.
Use: Image processing, Heavy calculation.24. Service Workers (PWA)
24. Service Workers (PWA)
25. CORS (Cross-Origin Resource Sharing)
25. CORS (Cross-Origin Resource Sharing)
Access-Control-Allow-Origin: *.
Preflight: OPTIONS request sent before complex requests (PUT/DELETE/Custom Headers).4. ES6+ Modern Features
26. Proxy & Reflect
26. Proxy & Reflect
27. Generators (`function*`)
27. Generators (`function*`)
yield) and Resume (next).
Use: Audio streaming, Massive iterators, Redux-Saga.
Two-way communication: iter.next(value) passes value BACK into generator.28. Modules (ESM vs CommonJS)
28. Modules (ESM vs CommonJS)
- CommonJS: Node default.
require(). Sync. Dynamic (can require inif). - ESM: Browser standard.
import. Async / Static analysis (Tree Shaking). Top-level await.
29. Symbol Type
29. Symbol Type
Symbol('foo') !== Symbol('foo').
Use: Private properties, Iterator Protocol (Symbol.iterator).30. Tagged Templates
30. Tagged Templates
styled-components and GraphQL (gql).31. Optional Chaining & Nullish Coalescing
31. Optional Chaining & Nullish Coalescing
obj?.prop: Returns undefined if null, doesn’t throw.??: Returns RHS only if LHS isnullorundefined.0 || 5-> 5 (Buggy if 0 is valid).0 ?? 5-> 0 (Correct).
32. `Set` and `Map` complexity
32. `Set` and `Map` complexity
Set is best way to remove duplicates: [...new Set(array)].33. BigInt
33. BigInt
2^53 - 1 (MaxSafeInteger).
Suffix n: 1234567890123456789n.
Cannot mix with Number (must cast).5. Functional Programming patterns
34. Currying
34. Currying
f(a, b, c) into f(a)(b)(c).
Use: Partial Application. Reusable helpers.35. Pure Functions
35. Pure Functions
- Deterministic: Same Input -> Same Output.
- No Side Effects: No HTTP calls, no mutating global state, no logging. Benefit: Testable, Memoizable.
36. Higher Order Functions (HOF)
36. Higher Order Functions (HOF)
map, filter, reduce, debounce.37. Composition (`pipe`)
37. Composition (`pipe`)
f(g(x)).38. Immutability
38. Immutability
Object.freeze() (Shallow). Immer.js (Draft state).6. Tricky Code Snippets
39. `[] == ![]`
39. `[] == ![]`
![]->false(Array is truthy).[] == false->[] == 0(Type coercion).'' == 0->0 == 0. -> True.
40. `typeof null`
40. `typeof null`
'object'.
Historical bug in JS execution of typeof. Null reference check.41. `var` Scope Leak
41. `var` Scope Leak
3, 3, 3.
Reason: var is function scoped. Shared reference i.
Fix: let i (Block scoped) or IIFE.42. `NaN == NaN`
42. `NaN == NaN`
Number.isNaN() or Object.is(NaN, NaN).43. Object Key Coercion
43. Object Key Coercion
456.
Reason: Keys become string "[object Object]". a has only one key.44. `0.1 + 0.2 === 0.3`
44. `0.1 + 0.2 === 0.3`
0.30000000000000004).
IEEE 754 Floating Point logic.
Fix: Math.abs(a - b) < Number.EPSILON.45. Array Holes (`map` behavior)
45. Array Holes (`map` behavior)
[empty x 3].
map skips empty slots.
Fix: a.fill(0).map(...).7. Performance & Security
46. Memory Leaks
46. Memory Leaks
- Global Variables:
window.data = hugeArray. - EventListeners: Forgetting
removeEventListener(SPA navigation). - Intervals:
setIntervalrunning forever. - Tools: Chrome DevTools Memory Tab (Heap Snapshot).
47. XSS (Cross Site Scripting)
47. XSS (Cross Site Scripting)
- Sanitize Input (DOMPurify).
- Escape Output (React/Angular do this auto).
- CSP (Content Security Policy) header.
48. CSRF (Cross Site Request Forgery)
48. CSRF (Cross Site Request Forgery)
- SameSite Cookie Attribute (
Strict/Lax). - CSRF Token (Hidden input sync with server).
49. Keyed Collections (`WeakSet`) in Security
49. Keyed Collections (`WeakSet`) in Security
WeakMap is essentially secure storage for private data if the key (object) is kept private.
Used in “Private Class Fields” polyfills.50. Web Assembly (Wasm)
50. Web Assembly (Wasm)
51. Tree Shaking
51. Tree Shaking
require) is hard to shake.52. Lazy Loading (Dynamic Import)
52. Lazy Loading (Dynamic Import)
53. Preload vs Prefetch
53. Preload vs Prefetch
- Preload: “I need this NOW”. High priority. (Hero Image, Main Font).
- Prefetch: “I might need this LATER”. Low priority. (Next page JS).
54. Virtualization (Windowing)
54. Virtualization (Windowing)
react-window).55. Deep Clone Performance
55. Deep Clone Performance
JSON.parse(JSON.stringify(obj)) is slow and loses Date/RegExp/undefined.
Better: structuredClone() (Native API).8. Miscellaneous
56. `requestAnimationFrame`
56. `requestAnimationFrame`
setTimeout for animations (Pauses in background tab).
Prevents screen tearing.57. `Intl` API
57. `Intl` API
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).58. `Object.seal` vs `Object.freeze`
58. `Object.seal` vs `Object.freeze`
- Seal: Cannot Add/Delete props. Can Modify existing values.
- Freeze: Absolute immutable. Can’t Add/Delete/Modify.
59. Iterators & Layout Thrashing
59. Iterators & Layout Thrashing
60. TCO (Tail Call Optimization)
60. TCO (Tail Call Optimization)
9. ES6+ Features (Medium Level)
61. Spread Operator vs Rest Parameters
61. Spread Operator vs Rest Parameters
- Spread (…): Expands an iterable into individual elements.
- Rest (…): Collects multiple elements into an array.
62. Array Methods: map, filter, reduce, flatMap
62. Array Methods: map, filter, reduce, flatMap
- map: Transform each element.
- filter: Select elements matching condition.
- reduce: Accumulate to single value.
- flatMap: Map + flatten one level.
63. Object Destructuring with Defaults
63. Object Destructuring with Defaults
64. Template Literals and Tagged Templates
64. Template Literals and Tagged Templates
65. Default Parameters
65. Default Parameters
66. Array.from() and Array.of()
66. Array.from() and Array.of()
- Array.from(): Create array from iterable.
- Array.of(): Create array from arguments.
67. Object.assign() vs Spread Operator
67. Object.assign() vs Spread Operator
68. for...of vs for...in Loops
68. for...of vs for...in Loops
- for…of: Iterate over values (iterables).
- for…in: Iterate over keys (properties).
69. String Methods: includes, startsWith, endsWith
69. String Methods: includes, startsWith, endsWith
70. Number Methods: isNaN, isFinite
70. Number Methods: isNaN, isFinite
71. JSON.stringify() and JSON.parse() Edge Cases
71. JSON.stringify() and JSON.parse() Edge Cases
72. Regular Expressions Basics
72. Regular Expressions Basics
73. Error Handling: try/catch/finally
73. Error Handling: try/catch/finally
74. setTimeout vs setInterval
74. setTimeout vs setInterval
- setTimeout: Execute once after delay.
- setInterval: Execute repeatedly.
75. Fetch API Basics
75. Fetch API Basics
76. FormData API
76. FormData API
77. URL and URLSearchParams
77. URL and URLSearchParams
78. Blob and File APIs
78. Blob and File APIs
79. Canvas API Basics
79. Canvas API Basics
80. Local Storage vs Session Storage
80. Local Storage vs Session Storage
10. Advanced JavaScript Patterns
81. Proxy Traps and Reflect API
81. Proxy Traps and Reflect API
82. WeakMap and WeakSet Use Cases
82. WeakMap and WeakSet Use Cases
83. Symbol.iterator and Custom Iterables
83. Symbol.iterator and Custom Iterables
84. Generator Delegation with yield*
84. Generator Delegation with yield*
85. Async Generators
85. Async Generators
86. SharedArrayBuffer and Atomics
86. SharedArrayBuffer and Atomics
87. FinalizationRegistry
87. FinalizationRegistry
88. Private Class Fields
88. Private Class Fields
89. Static Initialization Blocks
89. Static Initialization Blocks
90. Top-Level Await
90. Top-Level Await
91. Dynamic import()
91. Dynamic import()
92. Observable Pattern
92. Observable Pattern
93. Memoization
93. Memoization
94. Debounce vs Throttle
94. Debounce vs Throttle
95. Event Delegation
95. Event Delegation
96. Custom Events
96. Custom Events
97. Performance API
97. Performance API
98. IntersectionObserver
98. IntersectionObserver
99. MutationObserver
99. MutationObserver
100. Web Workers
100. Web Workers