JavaScript Senior
What is the difference between Lexical Scope and Dynamic Scope?
Select the correct answer
Lexical scope is set by where code is called; dynamic scope by where it is defined.
Lexical scope is set by where code is defined; dynamic scope by where it is called.
Lexical scope applies to objects; dynamic scope applies to functions and closures.
Lexical scope depends on the runtime call stack; dynamic scope on the file location.
Why does hoisting happen in JavaScript? Explain how the engine handles function declarations vs. variable declarations during the creation phase.
Select the correct answer
Both function and var declarations are hoisted fully along with their assigned values.
Function declarations are hoisted with their body; var declarations are hoisted as undefined.
Function declarations are hoisted as undefined; var declarations are hoisted with their values.
Neither is hoisted; the engine just reads them top to bottom during execution.
Why does [] + [] result in an empty string?
Select the correct answer
Each empty array is treated as the number zero, and adding zero to zero returns nothing.
The + operator on arrays merges their elements, and two empty arrays merge into nothing.
Arrays are converted to null, and concatenating null with null produces an empty string.
Each array is coerced to its primitive via toString(), giving empty strings that concatenate.
When would you use Object.create(null) instead of a standard object literal?
Select the correct answer
When you need a plain dictionary with no inherited prototype properties.
When you want to clone an object including all its inherited methods.
When you need an object that automatically freezes itself on creation.
When you want faster property lookups than a normal object literal.
Why does a Promise resolve before a setTimeout(0)?
Select the correct answer
Promise callbacks run as microtasks, which drain before any timer.
setTimeout enforces a minimum delay that Promise callbacks bypass.
Promise callbacks have higher thread priority than timer callbacks.
Promises run synchronously whereas setTimeout always defers its work.
What happens if a Promise is never resolved or rejected, and how does the engine handle this hanging state?
Select the correct answer
It automatically rejects with undefined once the event loop goes idle
It throws a timeout error after the default microtask queue empties out
It resolves to undefined as soon as all synchronous code finishes running
It stays pending forever and is garbage collected once it is unreferenced
What is the difference between the DOM, the Virtual DOM, and the Shadow DOM?
Select the correct answer
The DOM is a browser cache, the Virtual DOM is the real tree React renders, and the Shadow DOM is the parent document wrapping iframes
The DOM is the live tree, the Virtual DOM is an in-memory copy used for diffing, and the Shadow DOM scopes encapsulated subtrees
The DOM is rendered by the GPU, the Virtual DOM stores event listeners, and the Shadow DOM is a backup copy restored after reloads
The DOM is the live tree, the Virtual DOM hides elements from crawlers, and the Shadow DOM is an offscreen render buffer used internally
What is structuredClone and when would you use it over JSON.parse(JSON.stringify())?
Select the correct answer
It clones functions and DOM nodes along with data, producing an exact executable copy of any object
It deep-clones values including Date, Map, Set, and circular references that JSON cannot handle
It clones values faster by skipping nested objects, returning a shallow copy of only the top-level keys
It clones values into a frozen immutable object, preventing any further mutation unlike the JSON approach
Explain the difference between ES Modules (import/export) and CommonJS (require/module.exports). Why did the industry move toward ESM?
Select the correct answer
ESM runs only in Node.js whereas CommonJS is the native module system shipped inside browsers
ESM is statically analyzable and async, enabling tree-shaking; CommonJS loads dynamically and synchronously
ESM and CommonJS behave identically, but ESM uses shorter keywords for the same dynamic loading
ESM loads dynamically at runtime while CommonJS resolves all imports statically before execution
Explain the difference between Short Polling, Long Polling, and WebSockets. When is each appropriate?
Select the correct answer
Short polling sends periodic requests; long polling keeps each request open until data is ready; WebSockets maintain a persistent bidirectional link.
Short polling holds requests open indefinitely; long polling fires fixed-interval requests; WebSockets poll the server only when data exists.
Short polling uses bidirectional sockets; long polling streams data continuously; WebSockets close immediately after each server response.
Short polling keeps a socket open; long polling reconnects each time; WebSockets send periodic requests at fixed intervals from the server.
What is the iterable and iterator protocol in JavaScript?
Select the correct answer
An iterable requires a Symbol.asyncIterator method, and the iterator returns promises resolving to plain final values.
An iterable defines a next() method directly, while an iterator wraps it in a Symbol.iterator returning indexes.
An iterable exposes a Symbol.iterator method returning an iterator whose next() yields { value, done } objects.
An iterable is any array-like object, and an iterator is automatically created only for the built-in collection types.
Explain the Critical Rendering Path. How does JavaScript execution affect the parsing of HTML and CSS?
Select the correct answer
Scripts always run in parallel with HTML parsing and never block construction of the DOM or CSSOM trees.
CSS blocks script execution but scripts themselves never pause the parser or delay the very first paint.
JavaScript executes only after the page fully renders, so it can never affect parsing or the layout timing.
Synchronous scripts block HTML parsing and may wait on the CSSOM before executing, thereby delaying rendering.
How does the Event Loop decide when to perform a UI re-render in the browser?
Select the correct answer
Synchronously within each microtask as soon as the related promise gets resolved
Immediately after every DOM mutation occurs, before any queued task can be run next
After the microtask queue empties between tasks, throttled to the display refresh rate
Only once the call stack empties and every pending timer callback has already fired
What is the difference between a reflow and a repaint? Which one is more expensive, and how can you minimize them?
Select the correct answer
Reflow only redraws pixels and is cheaper; repaint reorders the entire DOM tree very slowly
Repaint rebuilds the render tree and is costlier; cache stored layout values to lower the cost
Repaint recalculates element positions and is costlier; avoid changing colors too frequently
Reflow recomputes layout geometry and is costlier; batch DOM reads and writes to reduce it
Explain the difference between microtasks and macrotasks. Which has priority, and why does it matter for UI responsiveness?
Select the correct answer
Microtasks run fully after each task before the next macrotask; they take priority over macrotasks
Macrotasks like promises run first; microtasks like timers wait until the stack fully clears out
Microtasks and macrotasks alternate one by one; neither one has priority over the rendering step
Macrotasks run fully between microtasks; they take priority to keep the UI responsive at all times
What happens to the Call Stack when an await keyword is encountered in an async function?
Select the correct answer
The function frame stays on the stack while later code runs concurrently on another thread
The stack blocks and waits on that frame until the awaited promise resolves with a value
The function suspends and is popped off the stack; its rest resumes later as a microtask
The entire stack is cleared immediately and all pending promises resolve in parallel order
What happens if a microtask recursively schedules another microtask, and what is starvation?
Select the correct answer
The engine caps microtasks per cycle, so recursion simply defers any leftover callbacks to later loop iterations.
Recursive microtasks become macrotasks, letting rendering proceed normally between each scheduled callback execution.
Each microtask waits one full event-loop tick, so recursion just spreads the work across many frames safely.
All microtasks run before the next task, so endless scheduling blocks macrotasks, that is starvation.
What is a 'Memory Leak' in JavaScript, and how can a closure or an event listener cause one?
Select the correct answer
Memory the engine allocates twice for one object, doubling heap usage whenever closures capture outer-scope variables.
Memory reserved by the engine for future allocations that closures and listeners permanently lock during their lifetime.
Memory no longer used but still referenced, so GC cannot free it; closures and listeners keep references alive.
Memory fragmentation caused by the collector failing to compact the heap after many event listeners are detached.
How does JavaScript's garbage collection (mark-and-sweep) work?
Select the correct answer
It periodically copies all live objects into a new region, then erases the entire old region in one pass.
It marks all objects reachable from the roots, then sweeps and frees every object left unmarked.
It scans the stack for stale objects, then moves long-lived ones into a separate permanent heap region.
It counts references to each object, then immediately frees any object whose reference count reaches zero.
What are deoptimizations in a JS engine, and what kind of code patterns usually trigger them?
Select the correct answer
Optimized code is discarded and the engine reverts to slower code when object shapes or types change.
A function is permanently disabled after errors, and the engine recompiles the whole script on the next call.
Several hot functions are merged into one, which often slows execution when their argument types differ widely.
Compilation is delayed until types stabilize, leaving frequently changing functions interpreted far more slowly.
What is a JavaScript Proxy, and what are some practical use cases for it (e.g., validation, logging)?
Select the correct answer
A function observing a target that fires callbacks after changes, commonly used for logging and debugging.
An object wrapping a target that uses traps to intercept operations, useful for validation and logging.
A wrapper that caches a target's properties for speed, often used to log access and validate cached values.
A frozen copy of a target object that blocks all writes, commonly used to enforce read-only validation rules.
What is Just-In-Time (JIT) compilation in engines like V8?
Select the correct answer
It compiles frequently executed bytecode into optimized machine code at runtime instead of interpreting it.
It translates the entire source file into machine code once before execution begins, like a static compiler.
It converts machine code back into bytecode whenever a function becomes hot, reducing the interpreter's workload.
It precompiles every function into native code during parsing, caching them on disk for faster future startups.