100 Most-Asked JavaScript Interview Questions
(Fresher, 2025)
Compiled for web■developer fresher roles • Updated: 10 Nov 2025
How to use this PDF
Each question comes with a short, self-explanatory answer. Wherever helpful, small code snippets
and mental models are included. Focus first on fundamentals (types, scope, hoisting, closures,
prototypes, async) and then browser/web APIs, DOM, performance, and security.
1. What is JavaScript and where does it run?
JavaScript is a high■level, prototype■based language used in browsers and servers ([Link]). It is
single■threaded with concurrency via the event loop.
2. Difference between JavaScript and ECMAScript?
ECMAScript is the specification; JavaScript is the implementation plus host APIs (DOM in browsers,
fs in Node).
3. List the primitive types in JavaScript.
string, number, bigint, boolean, null, undefined, symbol. Primitives are immutable; objects are
mutable.
4. Difference between == and === ?
== performs type coercion; === compares value and type without coercion. Prefer === for
predictability.
5. Explain hoisting.
Declarations are registered before execution. var is initialized to undefined; let/const are hoisted but
in the Temporal Dead Zone until declared. Functions are fully hoisted.
6. var vs let vs const.
var is function■scoped and re■declarable. let/const are block■scoped; const prevents reassignment
(object contents can still change).
7. What is the Temporal Dead Zone (TDZ)?
Time between entering scope and executing let/const declaration. Accessing the variable throws
ReferenceError.
8. Truthy vs falsy values.
Falsy: false, 0, -0, 0n, '', null, undefined, NaN. Everything else is truthy.
9. Type coercion in JS.
Implicit conversions happen in operations; explicit with Number(), String(), Boolean(). Be careful with
+ operator and comparisons.
10. What is NaN and how to check it?
NaN is 'Not■a■Number' (type number). Check with [Link](x) since NaN !== NaN.
11. Lexical scope.
Scope is determined by code placement. Inner functions access outer variables via the scope chain.
12. What is a closure?
A closure is a function plus its lexical environment, allowing it to access outer variables after the outer
function returns.
13. Use■cases of closures.
Privacy, function factories, partial application, memoization, event handlers with captured state.
14. Arrow functions vs regular functions.
Arrows lack their own this/arguments and capture this lexically; cannot be used as constructors.
15. How is 'this' bound?
By call■site: implicit ([Link]()), explicit (call/apply/bind), new binding (constructor), default binding
(undefined in strict mode).
16. call vs apply vs bind.
call(this,a,b), apply(this,[a,b]) invoke immediately; bind returns a new function with preset this/args.
17. map, filter, reduce.
map transforms, filter selects, reduce accumulates to a single value. All return new arrays.
18. forEach vs map.
forEach returns undefined (for side effects). map returns a new array with transformed values.
19. Debouncing vs throttling.
Debounce runs after a quiet period; throttle limits execution rate. Useful for scroll/resize.
20. Pure vs impure functions.
Pure: no side effects, deterministic. Impure touches external state (DOM, network, globals).
21. Prototypal inheritance.
Objects inherit via [[Prototype]] chain. [Link] and class syntax leverage this model.
22. Prototype chain lookup.
Property access checks own props, then walks up prototypes until null.
23. [Link] vs class.
[Link] sets prototype directly; class is syntactic sugar over constructor functions/prototypes.
24. Shallow vs deep copy.
Shallow copies first■level references; deep copy recursively copies (structuredClone is best modern
option).
25. Getters and setters.
Define computed/controlled access to properties for validation or derived values.
26. freeze vs seal vs preventExtensions.
freeze: no add/delete/change; seal: change allowed but no add/delete; preventExtensions: cannot
add.
27. Symbol.
Unique, immutable identifiers used as property keys and well■known hooks ([Link]).
28. Map/Set vs Object/Array.
Map has any■type keys and stable iteration; Set ensures uniqueness. Often faster for frequent
add/remove.
29. WeakMap/WeakSet.
Hold weak references so entries don't prevent GC; not iterable; great for private data/caches tied to
objects.
30. How 'new' works.
Creates empty object, sets prototype, binds this, runs constructor, returns object (unless constructor
returns another object).
31. Event loop.
Manages task queues: microtasks (promises) run before the next macrotask (setTimeout, I/O).
32. Promises and chaining.
Pending→fulfilled/rejected. then for success, catch for errors, finally always. Chaining returns new
promises.
33. async/await.
Syntactic sugar over promises. await pauses inside async; use try/catch to handle rejections.
34. [Link] vs race vs allSettled vs any.
all waits for all; race settles on first; allSettled waits for all to settle; any fulfills on first success.
35. Microtask vs macrotask ordering.
After synchronous code, microtasks run before the next macrotask.
36. setTimeout vs setInterval.
setTimeout runs once; setInterval repeats and can drift—use recursive timeouts or rAF for precision.
37. fetch error handling.
fetch only rejects on network errors. Check [Link] before parsing; handle app■level errors too.
38. CORS basics.
Server■controlled headers allow/deny cross■origin requests. Browser enforces policy for security.
39. JSON vs JS object.
JSON is a string format; JS object is in■memory. Convert via [Link]/parse.
40. AbortController.
Cancel fetch or other async tasks by passing signal and calling abort().
41. DOM vs BOM.
DOM: document tree of nodes. BOM: browser APIs like window, history, location, navigator.
42. DOMContentLoaded vs load.
DOMContentLoaded fires when DOM is parsed; load waits for all resources (images/styles).
43. Capturing vs bubbling; stopPropagation.
Events capture (down), target, then bubble (up). stopPropagation halts travel.
44. Event delegation.
Listen on a parent; use [Link] to handle child events—great for dynamic lists.
45. localStorage vs sessionStorage vs cookies.
localStorage persists; sessionStorage per■tab; cookies go to server (respect
SameSite/Secure/HttpOnly).
46. innerHTML vs textContent.
innerHTML parses HTML (XSS risk). textContent inserts text safely—use for untrusted data.
47. Preventing XSS.
Escape outputs, sanitize HTML, enable CSP, avoid eval/new Function, prefer textContent.
48. Web Components.
Custom Elements + Shadow DOM + templates enable encapsulated, reusable UI elements.
49. requestAnimationFrame.
Schedule animation updates before repaint; smoother than setInterval for UI.
50. IntersectionObserver.
Detect element visibility to lazy■load images or implement infinite scroll.
51. Destructuring with defaults.
Extract values with patterns; defaults apply when value is undefined.
52. Spread vs rest.
Spread expands values; rest collects arguments. Both use ... but in different contexts.
53. Template literals & tagged templates.
String interpolation and multi■line strings; tags can sanitize/process input before output.
54. Iterables & iterators.
Implement [Link] to become iterable; for..of consumes iterables.
55. Generators.
function* yields values and can pause/resume—useful for lazy sequences.
56. Optional chaining & nullish coalescing.
obj?.a?.b safely accesses; x ?? y uses y only if x is null/undefined.
57. BigInt.
Arbitrary■precision integers (123n). Don't mix with Number without conversion.
58. Modules: import/export vs require.
ESM is static and tree■shakeable; CommonJS is dynamic. Modern Node supports ESM.
59. Tree■shaking.
Remove unused exports in build to shrink bundle size.
60. Polyfills & transpilers.
Babel/TS down■level syntax; polyfills add missing runtime features (e.g., Promise).
61. Immutable array ops.
Use map/filter/slice/concat/toSorted to avoid mutation; prefer for UI state updates.
62. Array■like vs iterable.
Array■like have length/indexes; iterables define [Link]. Convert with [Link].
63. find vs findIndex vs includes.
find returns element; findIndex returns index; includes checks presence (supports NaN).
64. [Link] comparator.
Provide (a,b)=>a-b for numbers; sort mutates—use toSorted to keep original.
65. String utilities.
includes, startsWith, endsWith, slice/substring, replace/replaceAll, trim, padStart/End.
66. Number precision pitfalls.
Binary floating point causes 0.1+0.2≠0.3; format with toFixed; consider BigInt/decimal libraries for
money.
67. Date & time basics.
Use ISO strings and Intl for formatting; beware local vs UTC. Avoid manual month math.
68. Set operations.
Union/Intersection/Difference via Set and array helpers (filter, spread).
69. Regex essentials.
Use flags g/i/m/s/u/y; escape user input; test() and exec() for checks and matches.
70. Deep equality.
Recursive compare or libraries; JSON stringify has caveats (order, functions, undefined).
71. Front■end security basics.
Defend against XSS/CSRF/clickjacking with encoding, CSP, SameSite cookies, tokens,
frame■ancestors.
72. SameSite cookies.
Controls cross■site cookie sending: Strict, Lax, None (needs Secure). Helps prevent CSRF.
73. Critical rendering path.
Reduce render■blocking assets, defer/async scripts, inline critical CSS, compress and cache.
74. Code splitting.
Load only what’s needed initially; lazy■load routes/components to improve TTI.
75. Memoization.
Cache previous results for expensive pure functions; clears when inputs change.
76. Web storage vs IndexedDB.
Storage is simple key■value; IndexedDB is async transactional DB for larger structured data.
77. Service workers & caching.
Enable offline, background sync, push; design cache strategies carefully to avoid stale data.
78. Accessibility basics.
Use semantic HTML, proper labels/roles, keyboard support, focus management, ARIA sparingly.
79. Error handling strategy.
try/catch around await, global listeners, user■friendly messages, and privacy■safe logs.
80. Linting & formatting.
ESLint for rules; Prettier for consistent formatting; run in CI.
81. Node vs Browser.
Node has server APIs and no DOM; browsers have DOM/fetch/window. Module and globals differ.
82. NPM scripts & semver.
Use [Link] scripts; semver: [Link] with ^ and ~ ranges.
83. Environment variables.
Use [Link] in Node and build■time injection for front■end; never hard■code secrets.
84. HTTP methods & status codes.
Know GET/POST/PUT/PATCH/DELETE; 2xx success, 3xx redirect, 4xx client errors, 5xx server
errors.
85. REST vs GraphQL (client view).
REST is multiple endpoints; GraphQL queries specific fields from one endpoint; handle
caching/errors appropriately.
86. Unit testing in JS.
Jest/Vitest for units; test pure functions and user■visible DOM behavior with Testing Library.
87. Mocking fetch.
Stub network calls to keep tests fast/deterministic; verify requests and simulate responses.
88. E2E testing.
Playwright/Cypress automate browsers to test real flows; slower but catch integration bugs.
89. TypeScript benefits for JS devs.
Types catch errors early, improve IDE hints, and make refactors safer; can adopt gradually.
90. Bundlers/build tools.
webpack, Vite, Rollup manage modules/assets, dev servers, HMR, minification, tree■shaking.
91. Why does var in loops cause surprises with setTimeout?
var is function■scoped so callbacks share the final value. Use let (block scope) or IIFE to capture the
value per iteration.
92. Safe object cloning.
Use structuredClone when available; JSON stringify/parse loses functions/undefined; libraries handle
complex cases.
93. Module scope vs IIFE.
ES modules have file scope by default; older code used IIFEs to avoid polluting globals.
94. Preventing memory leaks.
Clean up listeners/timers, avoid globals, break circular refs, beware long■lived closures over large
objects.
95. this pitfalls in handlers.
Bind class methods or use arrows; in React function components there is no this—use hooks.
96. What is 'use strict'?
Strict mode removes some silent errors, changes default this to undefined, blocks certain bad
patterns.
97. Immutability and UI frameworks.
Immutable updates enable cheap change detection (shallow compare) and predictable state updates.
98. Handling slow APIs in UI.
Use skeletons/spinners, optimistic updates when safe, retries/backoff, and cancellation on navigation.
99. [Link] vs currentTarget.
target is the origin element; currentTarget is the element whose listener is running (often the
delegated parent).
100. CSP basics.
A security policy that whitelists allowed resource sources to reduce XSS risk (e.g., script-src).
Selected Code Snippets
Closure example:
function counter(){ let c = 0; return function(){ c += 1; return c; }; } const
inc = counter(); [Link](inc()); // 1 [Link](inc()); // 2
Event loop order:
[Link]('A'); queueMicrotask(()=>[Link]('micro'));
setTimeout(()=>[Link]('timeout'),0); [Link]('B'); // Order: A, B,
micro, timeout
Debounce utility:
function debounce(fn, delay){ let t; return (...args)=>{ clearTimeout(t); t =
setTimeout(()=>fn(...args), delay); }; }