Javascript
Javascript Interview Questions and Answers
1. What is JavaScript?
A: A high-level, interpreted programming language primarily used to make web pages interactive.
2. Is JavaScript the same as Java?
A: No. Despite similar names, they are different languages with different designs.
3. What type of language is JavaScript?
A: Dynamically typed, weakly typed, interpreted, prototype-based, multi-paradigm.
4. How do you declare a variable in JavaScript?
5. Difference between var, let, and const?
- var: function-scoped, hoisted, can be redeclared.
- let: block-scoped, cannot be redeclared in same scope.
- const: block-scoped, must be initialized, cannot be reassigned.
6. What does typeof do?
A: Returns the type of a variable as a string.
7. What is NaN?
A: Stands for “Not-a-Number”. Returned from invalid numeric operations.
8. How can you check if a value is NaN?
9. What is === vs ==?
==
: compares with type coercion.===
: strict equality, no type coercion.
10. What is a template literal?
Allows embedded expressions with backticks `` `.
11. What is a function?
A: A reusable block of code.
12. How to declare a function?
13. What is an anonymous function?
A: A function without a name.
14. What is an arrow function?
15. What does return do?
A: Exits the function and returns a value.
16. What is console.log?
A: Outputs messages to the browser console.
17. What are objects in JavaScript?
A: Collections of key-value pairs.
19. What is an array?
A: Ordered list of values.
20. How to loop through an array?
21. What is an if statement?
22. What is a ternary operator?
23. What is a switch?
24. What are logical operators?
- &&: AND
- ||: OR
- !: NOT
25. What does ?? do?
A: Nullish coalescing operator. Returns right-hand side if left is null or undefined.
26. What is scope?
A: Determines visibility of variables.
27. Difference between global and local scope?
- Global: accessible everywhere.
- Local: inside functions or blocks.
28. What is block scope?
A: Scope within braces (created by let, const).
29. What is function scope?
A: Scope created inside a function. var is function-scoped.
30. What is a closure?
A: A function that remembers variables from its outer scope.
31. Example of closure?
32. What is hoisting?
A: JavaScript moves declarations to the top. Functions fully hoisted; var is hoisted with undefined.
33. What are default parameters?
34. What is a rest parameter?
35. What is the spread operator?
36. What does Array.push do?
A: Adds to end.
37. What does pop do?
A: Removes last item.
38. How to remove first item?
39. How to add item to start?
40. What does slice do?
A: Returns a shallow copy of part of array.
41. What does splice do?
A: Changes array by adding/removing elements.
42. What is map?
A: Creates new array by transforming each element.
43. What is filter?
A: Creates array with elements that pass test.
44. What is reduce?
A: Accumulates array into single value.
45. How to check if array includes value?
46. How to get string length?
47. How to find substring?
48. What does toUpperCase do?
A: Converts string to uppercase.
49. What does split do?
50. How to replace text?
51. What does trim() do?
A: Removes whitespace from start and end.
52. What does startsWith() do?
A: Checks if string starts with substring.
53. How about endsWith()?
A: Checks if string ends with substring.
54. What is parseInt?
A: Converts string to integer.
55. What is parseFloat?
A: Parses string to floating-point number.
56. How to format number with 2 decimals?
57. What does isFinite check?
A: Whether a value is a finite number.
58. What is Math.random()?
A: Returns random float between 0 and 1.
59. How to round a number?
60. What does Math.floor do?
A: Rounds down.
61. What does Math.ceil do?
A: Rounds up.
62. What is Math.max and Math.min?
A: Finds highest or lowest of given numbers.
63. What is this?
A: Refers to the object the function is a method of.
64. How does this work in global scope?
A: In browser, this is window.
65. What does this refer to in an object method?
A: The object itself.
66. How does this work in a function?
A: By default refers to global object (window), or undefined in strict mode.
67. What is bind?
A: Creates new function with this bound to specific object.
68. What is call?
A: Calls function with this and arguments.
69. What is apply?
A: Same as call but takes arguments as array.
70. How does this work in arrow functions?
A: Inherits this from enclosing scope (lexical this).
71. What is Object.keys?
A: Returns array of object's own property names.
72. What is Object.values?
A: Returns array of values.
73. What is Object.entries?
A: Returns array of [key, value] pairs.
74. How to merge objects?
75. What is object destructuring?
76. What is nested destructuring?
77. How to clone an object?
78. What is prototype?
A: Mechanism by which objects inherit features from one another.
79. What is prototype chain?
A: Series of links through proto allowing property lookup.
80. What is a class?
81. How to create subclass?
82. What does super do?
A: Calls parent constructor or methods.
83. What is static method?
Called on class, not instance.
84. What is instanceof?
A: Tests if object is an instance of constructor.
85. What is hasOwnProperty?
A: Checks if property is direct (not inherited).
86. What is the DOM?
A: Document Object Model, represents HTML as a tree of objects.
87. How to select element by ID?
88. How to select by class?
89. How to use querySelector?
90. What is innerHTML?
A: Gets/sets HTML content inside element.
91. What is textContent?
A: Gets/sets text content only.
92. How to change style?
93. How to create element?
94. How to append child?
95. How to remove element?
96. How to add event listener?
97. What does preventDefault do?
A: Prevents default browser action.
98. What does stopPropagation do?
A: Stops event bubbling up.
99. What is event delegation?
A: Attach listener to parent, use event.target to handle children.
100. How to trigger click in JS?
103. What does .then() do?
A: Registers callbacks for promise resolution.
104. What does .catch() do?
A: Registers callback for promise rejection.
105. What does .finally() do?
A: Runs after promise settles, whether fulfilled or rejected.
106. How to run code asynchronously?
107. What is async function?
A: Always returns a promise.
108. What does await do?
A: Pauses inside async until promise settles.
109. Example of async/await?
110. What is Promise.all?
A: Runs promises in parallel, waits for all to resolve or any to reject.
111. What is Promise.race?
A: Resolves/rejects with the first settled promise.
112. What is Promise.allSettled?
A: Waits for all to finish, returns array of results {status, value/reason}
.
113. What is JSON?
A: JavaScript Object Notation, lightweight data format.
114. How to parse JSON?
115. How to convert to JSON?
116. What is let and const block scope good for?
A: Avoids variable hoisting surprises of var.
117. What are template literals?
Support multi-line strings and interpolation.
118. What are arrow functions not suitable for?
A: Using this dynamically (lexical this).
119. What are default parameters?
120. What is destructuring?
121. What is rest operator?
122. What is spread operator?
123. What is for...of?
Iterates values.
124. How about for...in?
A: Iterates keys of an object.
125. What are symbols?
A: Unique immutable primitive for keys.
126. What is a Set?
A: Collection of unique values.
127. How to add to Set?
128. How to check Set contains value?
129. What is Map?
A: Key-value pairs, where keys can be any type.
130. How to get value from Map?
131. How to iterate Map?
132. How to get keys from Map?
133. What does find do?
134. What is findIndex?
A: Returns index of first match.
135. What is some?
A: Checks if at least one element passes test.
136. What is every?
A: Checks if all elements pass test.
137. What is flat?
138. What is flatMap?
A: Maps then flattens one level.
139. What is an ES module?
140. What does import do?
A: Loads JS code from another file.
141. What does export mean?
A: Marks values to be available for import elsewhere.
142. Difference between default and named exports?
143. What is a bundler (Webpack, Parcel)?
A: Combines multiple JS files into one for production.
144. What is Babel?
A: JavaScript compiler for transforming ES6+ to ES5.
145. What is tree shaking?
A: Eliminates unused code in bundling.
146. How to handle errors?
147. What is finally for?
A: Runs after try or catch always.
148. How to throw error?
149. How to set timeout?
150. How to clear timeout?
151. What is setInterval?
A: Repeats function every delay.
152. How to cancel interval?
153. What is a higher-order function?
A: Takes functions as args or returns function.
154. What is pure function?
A: No side-effects, same inputs -> same output.
155. What is immutability?
A: Avoid changing data directly.
156. What is currying?
157. What is memoization?
A: Cache results of expensive calls.
158. What is typeof null?
A: 'object' (quirk).
159. What is NaN === NaN
?
A: false.
160. How to check NaN reliably?
161. What does delete do?
A: Removes property from object.
162. What does void operator do?
163. What is IIFE?
A: Immediately Invoked Function Expression.
164. What is strict mode?
Throws more errors, disables sloppy behavior.
165. What is arguments object?
A: Array-like object of all args inside function.
166. How to get current URL?
167. How to alert a message?
168. How to confirm a choice?
169. How to prompt for input?
170. How to listen for window resize?
171. How to scroll to top?
172. How to get viewport size?
173. How to block context menu?
174. What is localStorage?
A: Key-value store, persists across sessions.
175. What is sessionStorage?
A: Key-value store cleared on tab close.
176. How to set item in localStorage?
177. How to retrieve item?
178. How to remove item?
179. What is debounce?
A: Delay running function until user stops triggering it.
180. What is throttle?
A: Run function at most once per time period.
181. Why minimize DOM manipulation?
A: Slow due to reflows/repaints.
182. What is virtual DOM?
A: Lightweight copy used to optimize re-rendering (React).
183. Why bundle/minify JS?
A: Fewer requests, faster loading.
184. What does defer in <script>
tag do?
A: Runs after HTML parsed.
185. What does async do?
A: Loads script asynchronously, may run before HTML complete.
186. What is console.dir?
A: Prints an interactive listing of object.
187. How to break on debugger?
188. What is unit testing?
A: Testing individual functions/components.
189. Popular JS test frameworks?
A: Jest, Mocha, Jasmine.
190. What is TDD?
A: Test Driven Development.
191. What is linting?
A: Static analysis to find problems (ESLint).
192. What is CORS?
A: Cross-Origin Resource Sharing, controls requests from other domains.
193. What is XSS?
A: Cross Site Scripting.
194. How to mitigate XSS?
A: Sanitize inputs, escape outputs.
195. What is transpilation?
A: Converting newer JS into older version for compatibility.
196. How to check browser support?
A: CanIUse.com or @supports.
197. What is polyfill?
A: JS that adds missing feature in older browsers.
198. What is transpiler vs compiler?
A: Transpiler: same-level languages (ES6 to ES5). Compiler: any language to machine code.
199. What is graceful degradation?
A: Build for newest, still works on old.
200. What is progressive enhancement?
A: Build for baseline, enhance with JS.
201. What is a callback?
A: A function passed to another function to be executed later.
202. What is callback hell?
A: Nested callbacks making code hard to read & maintain.
203. How does promise solve callback hell?
A: Allows chaining with .then() and better error handling.
204. What is the module pattern?
A: Uses closures to emulate private/public.
205. What is the revealing module pattern?
A: Returns object literal exposing inner functions.
206. What is an immediately invoked arrow function (IIFE)?
207. What is function composition?
A: Combining functions so output of one becomes input of next.
208. What is partial application?
A: Pre-filling some arguments.
209. What is tail call optimization?
A: Reuses stack frame for recursive call (not widely supported).
210. What is monad in JS?
A: Design pattern to chain computations (seen in libraries like Ramda).
211. What is optional chaining?
Avoids errors if property doesn’t exist.
212. What is nullish coalescing?
Only falls back on null or undefined.
213. What are logical assignment operators?
214. What is Promise.any?
A: Resolves on first fulfilled promise, ignores rejections.
215. What is globalThis?
A: Cross-environment global object (browser window, Node global).
216. What is BigInt?
217. What is dynamic import()?
A: Loads modules on demand.
218. What is WeakRef?
A: Holds weak reference to object (used with finalization).
219. What is Intl?
A: Built-in internationalization API.
220. What is garbage collection?
A: JS automatically frees memory no longer reachable.
221. What causes memory leaks?
A: Unreleased references, listeners not removed.
222. How to find memory leaks?
A: Browser DevTools -> Memory tab.
223. What is a detached DOM tree?
A: DOM nodes kept alive by JS references even if removed from document.
224. Why sanitize user input?
A: To prevent XSS attacks.
225. What is CSP (Content Security Policy)?
A: HTTP header to restrict sources of scripts.
226. How to mitigate CSRF?
A: Use tokens tied to session.
227. Why avoid eval?
A: Runs arbitrary code, security & performance issues.
228. What is strict mode used for security?
A: Eliminates silent errors, makes assignments safer.
229. What is IntersectionObserver?
A: Asynchronously observes changes in intersection of element and viewport.
230. What is MutationObserver?
A: Watches DOM changes.
231. What is ResizeObserver?
A: Notifies when element’s size changes.
232. What is fetch API?
Modern way to make HTTP requests.
233. What is AbortController?
A: Cancels fetch requests.
234. What is History API?
A: Lets you push/replace state to URL without reload.
235. What is navigator.geolocation?
A: Get user location.
236. What is Notification API?
A: Display system notifications.
237. What is WebSocket?
A: Persistent connection for bi-directional data.
238. What is localStorage vs indexedDB?
- localStorage: simple key-value strings.
- indexedDB: structured, larger datasets.
239. What is mocking?
A: Faking modules/APIs for tests.
240. What is snapshot testing?
A: Captures output and compares on next runs (common in Jest).
241. What is coverage?
A: % of code run by tests.
242. How to inspect event listeners in browser?
A: DevTools -> Event Listeners tab.
243. What is requestAnimationFrame?
A: Schedules animation for next repaint.
244. Why prefer over setTimeout for animations?
A: Syncs with display refresh, more efficient.
245. What is dataset?
Access data-*
attributes.
246. What is classList?
247. What is closest?
A: Finds nearest ancestor matching selector.
248. What is focus & blur?
249. What is scrollIntoView?
A: Scrolls element into viewport.
250. What is Element.getBoundingClientRect()?
A: Returns position & size relative to viewport.
251. What is map vs forEach?
- map: returns new array.
- forEach: just iterates.
252. What is immutability good for?
A: Easier reasoning, avoids side-effects.
253. How to deeply clone object?
A: structuredClone(obj) or JSON approach.
254. What is declarative vs imperative?
- Declarative: describe what.
- Imperative: step by step how.
255. What is pure vs impure function?
- Pure: always same output, no side effects.
- Impure: relies on or modifies outside state.
256. What happens on 0.1 + 0.2 === 0.3
?
A: false
due to floating point precision.
257. What does []
+ []
produce?
A: ""
(empty string).
258. What does []
+ {}
produce?
A: "[object Object]"
.
259. What does {}
+ []
give?
A: 0
, due to parsing as block + array.
260. What is service worker?
A: Background script enabling offline, caching.
261. What is progressive web app (PWA)?
A: Web app with offline & native-like features.
262. What is shadow DOM?
A: Encapsulated DOM tree inside component.
263. What are web components?
A: Reusable custom HTML elements.
264. What is custom event?
265. How to lazy load images?
266. What is matchMedia?
A: Runs JS for media query matches.
267. What is ResizeObserver vs MutationObserver?
- ResizeObserver: watches size.
- MutationObserver: watches DOM changes.
268. What is navigator.clipboard?
A: Async clipboard API.
269. What is document.execCommand?
A: Old synchronous clipboard commands.
270. What is performance.now()?
A: High-resolution timestamp.
271. What is event loop?
A: Handles execution of code, events & tasks.
272. What are microtasks vs macrotasks?
- Microtasks: promises, queueMicrotask.
- Macrotasks: setTimeout, setInterval.
273. Example of microtask queue order?
274. What is debounce vs throttle?
A: Debounce waits until stop, throttle limits calls.
275. What is observer pattern?
A: Object notifies dependents on change.
276. What is pub/sub?
A: Publisher emits events, subscribers listen.
277. What is middleware?
A: Functions that process requests in order (common in express, redux).
278. What is polyfill vs shim?
- Polyfill: implements missing feature.
- Shim: wraps existing behavior to improve it.
279. Why avoid long JS tasks?
A: Blocks UI thread.
280. How to break long loop?
281. How to test DOM events?
A: Simulate with dispatchEvent or test frameworks.
282. How to mock API calls?
A: Jest mock functions or libraries like MSW.
283. How to handle timezone issues?
A: Use libraries like date-fns or Intl.
284. How to handle currency?
A: Use Intl.NumberFormat.
285. What’s your approach to optimizing performance?
A: Profile, minimize repaints, lazy load, use will-change.
286. How to debug memory leak?
A: Snapshots in Chrome Memory panel.
287. How do you handle cross-browser issues?
A: Use feature detection, polyfills, check on CanIUse.
288. How to ensure accessibility?
A: Use ARIA, semantic HTML, test with screen readers.
289. When would you use reduce vs map?
A: reduce to aggregate, map to transform array.
290. How to secure frontend?
A: Avoid inline scripts, use CSP, sanitize inputs.
291. How to lazy load JS modules?
292. How to optimize bundle size?
A: Tree shaking, dynamic imports, code splitting.
293. Why prefer fetch over XMLHttpRequest?
A: Simpler, promise-based.
294. What does await block?
A: Only async function execution, not entire thread.
295. How to share data across tabs?
A: Use localStorage events or BroadcastChannel API.
296. How to create delay with promises?
297. How to clone array without references?
298. How to debounce input?
299. What is stale closure?
A: Function captures old variables, common bug in loops or state.
300. What excites you about modern JavaScript?
A: (Open-ended: mention ESNext, async/await, PWA, WebAssembly, TypeScript...)