Vanilla JavaScript
Beginner (1-60)
Q001: What is JavaScript?
JavaScript is a programming language used to make web pages interactive. It runs in browsers and also on servers (for example, with Node.js). In this file, “Vanilla JavaScript” means JavaScript without external frameworks.
Q002: Why is it called “Vanilla JavaScript”?
“Vanilla” means plain/original JavaScript without libraries like React, Vue, or jQuery.
Q003: Where does JavaScript run in the browser?
JavaScript runs in the browser’s JavaScript engine (like V8 in Chrome). It can read and modify HTML/CSS through browser APIs (DOM, fetch, events, etc.).
Q004: How do you add JavaScript to an HTML page?
You can use:
- Inline script tags in HTML
- External .js files using <script src="…"></script>
Best practice: keep code in external files for maintainability.
Q005: What is the difference between script in <head> and end of <body>?
Script in <head> may run before HTML is parsed unless defer/async is used. Placing script before </body> ensures DOM is loaded first. Modern best practice: use defer in <head> for external scripts.
Q006: What does `defer` do?
`defer` downloads script in parallel and executes it after HTML parsing is complete. It preserves script order across deferred scripts.
Q007: What does `async` do?
`async` downloads script in parallel and executes as soon as ready. Order is not guaranteed between async scripts.
Q008: What is a variable?
A variable stores a value in memory so you can reuse and change it in code.
Q009: Difference between let, const, and var?
- let: block-scoped, reassignable
- const: block-scoped, not reassignable
- var: function-scoped, older behavior (hoisting quirks)
Prefer const by default, let when reassignment is needed.
Q010: What are primitive types in JavaScript?
Common primitives:
- string
- number
- bigint
- boolean
- undefined
- null
- symbol
Q011: What is an object in JavaScript?
An object is a collection of key-value pairs. It can store data and behavior (methods).
Q012: What is dynamic typing?
Variable types are determined at runtime. A variable can hold different types at different times.
Q013: What is `typeof`?
`typeof` returns the type description of a value (for example, "string", "number", "object", "undefined").
Q014: Why is `typeof null` equal to "object"?
It is a historical JavaScript bug preserved for backward compatibility.
Q015: What is `undefined`?
`undefined` means a value has not been assigned yet (default for uninitialized variables).
Q016: What is `null`?
`null` is an intentional “no value” assignment by developer choice.
Q017: Difference between = and ==?
- `==` does type coercion before comparison
- `===` compares value and type strictly
Prefer `===` for predictable behavior.
Q018: What is type coercion?
Automatic type conversion by JavaScript during operations/comparisons. Example: "5" + 1 -> "51"
Q019: What are truthy and falsy values?
Falsy values include: false, 0, -0, "", null, undefined, NaN. Everything else is truthy.
Q020: What is NaN?
NaN means “Not-a-Number,” representing an invalid numeric result.
Q021: How do you convert string to number?
Use Number(value), parseInt(value, 10), or parseFloat(value) depending on need.
Q022: What is a template literal?
String syntax using backticks that supports interpolation: `Hello ${name}`
Q023: What are JavaScript operators?
Symbols for calculations/comparisons/logical operations, e.g. +, -, *, /, &&, ||, !, >, =.
Q024: What is short-circuiting?
Logical operators may stop early:
- `a && b`: if a is falsy, b is not evaluated
- `a || b`: if a is truthy, b is not evaluated
Q025: What is nullish coalescing (`??`)?
Returns right side only if left side is null or undefined. Useful when 0 or "" are valid values.
Q026: What is optional chaining (`?.`)?
Safely accesses nested properties: user?.profile?.name If any step is null/undefined, result is undefined (no crash).
Q027: What is a function?
A reusable block of code that can accept inputs and return output.
Q028: Function declaration vs function expression?
- Declaration: hoisted with function body
- Expression: assigned to variable; follows variable initialization rules
Q029: What is an arrow function?
Short function syntax: `(a, b) => a + b` Arrow functions do not have their own `this`.
Q030: What does `return` do?
It ends function execution and sends a value back to caller.
Q031: What are parameters and arguments?
Parameters are function placeholders. Arguments are actual values passed during function call.
Q032: What are default parameters?
Parameters with fallback values: `function greet(name = "Guest") { … }`
Q033: What is scope?
Scope defines where variables are accessible (global, function, block).
Q034: What is block scope?
Variables declared with let/const inside {} exist only in that block.
Q035: What is hoisting?
JavaScript concept where declarations are processed before execution. `var` is hoisted differently from let/const (temporal dead zone applies to let/const).
Q036: What is temporal dead zone (TDZ)?
Period between block start and variable declaration where let/const cannot be accessed.
Q037: What is an array?
An ordered collection of values accessed by index (starting at 0).
Q038: Common array methods for beginners?
push, pop, shift, unshift, includes, indexOf, slice, splice.
Q039: Difference between slice and splice?
- slice: returns copy, does not mutate original
- splice: modifies original array
Q040: What is object destructuring?
Extracting object properties into variables: `const {name, age} = user`
Q041: What is array destructuring?
Extracting array elements by position: `const [first, second] = arr`
Q042: What is spread syntax (`…`)?
Expands iterable/object values. Examples:
- copy array: `[…arr]`
- merge object: `{…a, …b}`
Q043: What is rest parameter (`…args`)?
Collects remaining arguments into an array in function parameters.
Q044: What is a loop?
A control structure that repeats code while a condition is true.
Q045: Common loop types?
for, while, do…while, for…of, for…in (with care).
Q046: Difference between for…of and for…in?
- for…of iterates values (arrays/iterables)
- for…in iterates keys/properties (objects)
Q047: What is DOM?
Document Object Model: browser representation of HTML as a tree of nodes.
Q048: How do you select elements in DOM?
Common methods: querySelector, querySelectorAll, getElementById, getElementsByClassName.
Q049: How do you change text in an element?
Use textContent or innerText. Prefer textContent for predictable behavior and speed.
Q050: How do you change HTML inside an element?
Use innerHTML. Be careful: inserting untrusted HTML can create XSS security issues.
Q051: How do you change CSS with JavaScript?
- element.style.property = value
- element.classList.add/remove/toggle for class-based styling
Q052: What is an event?
An action detected by browser (click, input, submit, keydown, load, etc.).
Q053: How do you listen to events?
Use addEventListener: element.addEventListener("click", handler)
Q054: What is event handler?
Function that runs when an event occurs.
Q055: What is event object?
Object passed to handler containing event details (target, key, coordinates, etc.).
Q056: What is preventDefault()?
Stops default browser behavior (for example, prevent form submit reload).
Q057: What is stopPropagation()?
Stops event from bubbling to parent elements.
Q058: What is localStorage?
Browser storage for key-value strings persisted across sessions.
Q059: sessionStorage vs localStorage?
- sessionStorage: cleared when tab/session ends
- localStorage: persists until cleared manually/programmatically
Q060: Why use JSON.stringify and JSON.parse with storage?
Storage values are strings. Use stringify to save objects; parse to restore objects.
Intermediate (61-130)
Q061: What is execution context?
Environment where code runs, containing scope, variables, and `this` binding.
Q062: What is call stack?
Stack structure tracking function calls. If too deep (infinite recursion), stack overflow happens.
Q063: What is closure?
A closure is a function that remembers variables from lexical scope even after outer function finishes.
Q064: Why are closures useful?
Data privacy, function factories, memoization, maintaining state between calls.
Q065: What is lexical scope?
Scope determined by where functions are written, not where they are called.
Q066: What is `this` in JavaScript?
`this` refers to calling context. It depends on how function is called (object method, constructor, standalone, bound).
Q067: Arrow function and `this`?
Arrow functions capture `this` from surrounding scope; they do not bind their own `this`.
Q068: What do call, apply, and bind do?
They control `this` explicitly:
- call(thisArg, a, b)
- apply(thisArg, [a, b])
- bind(thisArg) returns new function
Q069: What is prototype in JavaScript?
Objects can inherit from other objects via prototype chain. Shared methods often live on constructor/class prototype.
Q070: What is prototypal inheritance?
Objects inherit properties/methods from prototype ancestors.
Q071: What is class syntax in JavaScript?
A cleaner syntax over prototypes for creating constructor + methods.
Q072: Constructor function vs class?
Both create objects; class is syntactic sugar with clearer structure.
Q073: What is `new` keyword doing?
Creates new object, links prototype, binds `this`, runs constructor, returns object.
Q074: What are getters and setters?
Special object/class methods for controlled reading/writing properties.
Q075: What is encapsulation in JS?
Keeping internal state private and exposing controlled public interface.
Q076: How can you emulate private fields?
Use:
- `#privateField` in classes
- closures
- module scope variables
Q077: What is module in JavaScript?
A file with its own scope that can export/import values.
Q078: What is ES module syntax?
- export / export default
- import {x} from "./file.js"
- import x from "./file.js"
Q079: Why modules improve code quality?
Separation of concerns, reuse, clear dependencies, less global pollution.
Q080: What is strict mode (`"use strict"`)?
Enables stricter parsing/errors and avoids dangerous legacy behaviors.
Q081: What is event loop?
Mechanism coordinating call stack and asynchronous callbacks/tasks in JS runtime.
Q082: What are Web APIs?
Browser-provided features like DOM, fetch, setTimeout, geolocation, etc.
Q083: What is callback?
Function passed to another function to run later, often after async operation.
Q084: What is callback hell?
Deeply nested callbacks causing unreadable and hard-to-maintain code.
Q085: What is a Promise?
Object representing future completion/failure of async operation.
Q086: Promise states?
pending -> fulfilled or rejected.
Q087: How to consume promise?
Use `.then(…)`, `.catch(…)`, `.finally(…)`.
Q088: What is async/await?
Syntax on top of promises that makes async code read like synchronous code.
Q089: Why use try/catch with async/await?
To catch rejected promises/errors in clean, linear style.
Q090: What does `await` do?
Pauses async function execution until promise settles, then resumes with result/error.
Q091: What is fetch API?
Built-in promise-based API for HTTP requests.
Q092: How to check fetch errors correctly?
Network failures reject promise. HTTP 4xx/5xx usually do NOT reject; check `response.ok` manually.
Q093: What is JSON in web apps?
Text format for data exchange. Use `response.json()` to parse JSON response body.
Q094: What is debouncing?
Delay function execution until user stops triggering event for a specified time.
Q095: What is throttling?
Limit function execution to once per interval during frequent events.
Q096: Why debounce/throttle?
Improve performance on input, scroll, resize, and mousemove-heavy interactions.
Q097: What is event delegation?
Attach one listener to parent and handle child events via bubbling. Efficient for dynamic lists/tables.
Q098: What is bubbling?
Event starts at target and propagates upward through ancestors.
Q099: What is capturing?
Event travels from root downward before reaching target (if capture phase listener used).
Q100: What is DOMContentLoaded?
Event fired when initial HTML is parsed (before all images/styles may finish).
Q101: What is reflow (layout)?
Browser recalculates element geometry/positions after DOM/style changes.
Q102: What is repaint?
Browser redraws visual appearance when style changes without layout changes.
Q103: Why minimize layout thrashing?
Repeated read/write layout operations can hurt performance. Batch DOM reads and writes.
Q104: What is requestAnimationFrame?
API for scheduling visual updates before next repaint, ideal for smooth animations.
Q105: setTimeout vs requestAnimationFrame?
setTimeout uses time delay; rAF syncs with display refresh for smoother UI updates.
Q106: What is memory leak in frontend JS?
Memory that is no longer needed but still referenced, so garbage collector cannot free it.
Q107: Common causes of memory leaks?
Detached DOM references, forgotten event listeners, long-lived closures, global caches.
Q108: What is garbage collection?
Automatic memory cleanup for unreachable objects.
Q109: What is shallow copy vs deep copy?
- Shallow: copies top level only
- Deep: copies nested structures too
Spread/Object.assign are shallow for objects.
Q110: What is immutability and why useful?
Do not modify existing data directly; create new versions. Helps predictability, debugging, and state tracking.
Q111: What is map()?
Creates new array by transforming each element.
Q112: What is filter()?
Creates new array containing elements that pass a condition.
Q113: What is reduce()?
Accumulates array into single value (sum, object map, grouped data, etc.).
Q114: What is find()?
Returns first element matching condition or undefined.
Q115: What is some() and every()?
- some: true if at least one element matches
- every: true if all elements match
Q116: What is sort() caveat?
Default sort compares strings. For numeric sorting use comparator: (a, b) => a - b.
Q117: What is Set?
Collection of unique values.
Q118: What is Map?
Key-value collection where keys can be any type (not just strings like plain object keys).
Q119: When to use Map over Object?
When keys are dynamic/non-string or frequent insert/delete/iteration needs.
Q120: What is regex?
Pattern language for matching/searching/modifying strings.
Q121: What is try/catch/finally?
Error handling blocks:
- try: risky code
- catch: handle error
- finally: always runs
Q122: throw vs Error object?
Use `throw new Error("message")` to throw structured errors with stack trace.
Q123: What is defensive programming in JS?
Validate inputs, handle null/undefined, fail gracefully, and provide useful errors.
Q124: What is idempotent UI action?
Action that can run multiple times with same effect (important in retries/re-renders).
Q125: Why avoid global variables?
They increase coupling, naming conflicts, and unpredictable side effects.
Q126: What is single responsibility principle in JS functions?
Each function should do one clear task. Smaller focused functions are easier to test and maintain.
Q127: What is pure function?
Function with same output for same input and no side effects.
Q128: What are side effects?
External changes: DOM mutation, logging, network calls, changing outside variables.
Q129: Why separate business logic from DOM logic?
Improves testability and reuse; DOM-specific code remains thin and manageable.
Q130: What is progressive enhancement?
Start with basic working HTML, then add JS enhancements for capable browsers.
Advanced/Expert (131-180)
Q131: What is microtask queue vs macrotask queue?
- Microtasks: Promise callbacks, queueMicrotask (higher priority after current stack)
- Macrotasks: setTimeout, setInterval, UI events
Event loop drains microtasks before next macrotask/render step.
Q132: Why can too many microtasks freeze UI?
If microtasks keep scheduling microtasks, browser may delay rendering and user interactions.
Q133: What is race condition in JavaScript apps?
Outcome depends on timing of async operations. Example: slower earlier request overwriting newer result.
Q134: How to prevent stale async UI updates?
Track request version/token, abort old requests, or compare latest query before render.
Q135: What is AbortController used for?
Cancel fetch or other abortable async operations to avoid wasted work/stale results.
Q136: What is optimistic UI update?
Update UI immediately assuming success, then rollback if server fails.
Q137: Benefits and risks of optimistic updates?
Better perceived speed; risk of inconsistency if failure handling is weak.
Q138: What is eventual consistency in frontend context?
UI/local state may temporarily differ from server but converges after sync.
Q139: What is hydration mismatch concept (general)?
When server-rendered markup and client-rendered output differ. Even in vanilla-like SSR setups, deterministic rendering is important.
Q140: What is CSP (Content Security Policy)?
Browser security policy restricting resource execution/loading to reduce XSS risk.
Q141: How does XSS happen in JavaScript apps?
Untrusted input is inserted/executed as HTML/script. Avoid unsafe innerHTML with untrusted data; sanitize content.
Q142: What is CSRF at high level?
Attacker tricks authenticated browser into sending unintended requests. Mitigate with CSRF tokens, same-site cookies, origin checks.
Q143: Why is input validation needed both client and server?
Client validation improves UX, but server validation is mandatory for security/integrity.
Q144: What is same-origin policy?
Browser restricts scripts from accessing resources across different origin (scheme+host+port).
Q145: What is CORS?
Mechanism allowing controlled cross-origin requests via HTTP headers.
Q146: Preflight request in CORS?
Browser sends OPTIONS request first for certain cross-origin requests to verify permissions.
Q147: What is caching strategy in frontend?
Use cache headers, local cache, service workers, and invalidation rules for speed + freshness.
Q148: What is cache busting?
Changing asset URL (often with hash/version) so browser fetches updated file.
Q149: Why use content hashes in JS/CSS filenames?
Ensures long-term caching while automatically invalidating when content changes.
Q150: What is Service Worker?
Script running in background to intercept requests, enable offline behavior, and caching strategies.
Q151: Common service worker caching patterns?
Cache-first, network-first, stale-while-revalidate (depends on resource type).
Q152: What is lazy loading in JS apps?
Loading code/resources only when needed (routes/components/images), reducing initial load.
Q153: What is code splitting concept without frameworks?
Break app into multiple JS modules loaded dynamically (`import()`).
Q154: What is tree shaking (concept)?
Build tools remove unused exported code from bundles.
Q155: Why minimize bundle size?
Smaller downloads = faster parse/execute, better performance on slow networks/devices.
Q156: What is long task in performance analysis?
Main-thread task > 50ms that can block interaction and cause jank.
Q157: What are Web Workers?
Background threads for CPU-heavy work without blocking main UI thread.
Q158: What can’t Web Workers directly do?
Workers cannot directly access DOM.
Q159: postMessage in workers?
Used to send messages/data between main thread and worker.
Q160: What is structured cloning?
Algorithm used by postMessage to copy complex data safely between contexts.
Q161: What is design pattern: module pattern?
Encapsulates private state and exposes public API, often using closures.
Q162: What is factory function pattern?
Function that returns configured objects, often cleaner than classes for some cases.
Q163: What is observer/publisher-subscriber pattern?
Components subscribe to events and get notified when publisher emits updates.
Q164: Why use pub/sub in vanilla apps?
Decouples modules and simplifies cross-component communication.
Q165: What is dependency injection (DI) in plain JS?
Pass dependencies as parameters instead of importing/creating internally. Improves testability and flexibility.
Q166: What is testability in JavaScript architecture?
How easily code can be verified automatically with unit/integration tests.
Q167: What makes JS code easy to test?
Pure functions, small modules, clear inputs/outputs, minimized global/DOM coupling.
Q168: What is mocking/stubbing concept?
Replace real dependencies (network/time/storage) with controllable test doubles.
Q169: What is deterministic code?
Same input/environment always produces same output. Determinism reduces flaky behavior.
Q170: How to handle time-dependent code safely?
Wrap Date/time APIs behind abstraction and inject clock in tests.
Q171: What is feature detection?
Check capability before using API: `if ("geolocation" in navigator) { … }` Better than browser sniffing.
Q172: Why avoid user-agent sniffing?
UA strings can be misleading/spoofed. Feature detection is more reliable and future-proof.
Q173: What is backward compatibility strategy?
Use progressive enhancement, polyfills where needed, and graceful degradation.
Q174: What is a polyfill?
Code that adds missing modern API behavior in older environments.
Q175: What is semantic error handling strategy in JS apps?
Classify errors (network, validation, auth, server) and map each to clear user feedback + retries.
Q176: What is retry with exponential backoff?
Retry with exponential backoff means each retry waits longer than the previous one (for example: 500ms, 1s, 2s, 4s) instead of retrying immediately. This reduces pressure on unstable services and improves recovery behavior. Best practice: add random jitter so many clients do not retry at exactly the same time.
Q177: What is circuit breaker pattern (frontend-friendly view)?
A circuit breaker temporarily stops repeated calls to a failing dependency. States are commonly:
- Closed: requests flow normally
- Open: requests are blocked/fail-fast for a cooldown period
- Half-open: limited test requests allowed
This prevents cascading failures and improves user experience during outages.
Q178: What is graceful degradation in JavaScript apps?
Graceful degradation means the app still works with reduced features when advanced APIs fail or are unavailable. Example: if geolocation is unavailable, allow manual location entry. Goal: keep core user flows usable under imperfect conditions.
Q179: What is progressive rendering and why does it help perceived performance?
Progressive rendering shows useful UI as soon as possible instead of waiting for everything. Examples:
- Render layout/skeleton first
- Show partial data as it arrives
- Lazy-load non-critical sections
Users perceive the app as faster because they can start interacting earlier.
Q180: How do expert developers keep Vanilla JavaScript projects maintainable at scale?
They use clear architecture and disciplined practices:
- Small focused modules
- Separation of UI, state, and business logic
- Consistent naming and folder conventions
- Defensive error handling and observability
- Performance budgets and profiling
- Automated tests for critical paths
- Accessibility and security checks in regular review
The key idea: maintainability is a design choice, not an afterthought.