JavaScript Senior

1 / 22

What is the difference between Lexical Scope and Dynamic Scope?

Select the correct answer

1

Lexical scope is set by where code is called; dynamic scope by where it is defined.

2

Lexical scope is set by where code is defined; dynamic scope by where it is called.

3

Lexical scope applies to objects; dynamic scope applies to functions and closures.

4

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

1

Both function and var declarations are hoisted fully along with their assigned values.

2

Function declarations are hoisted with their body; var declarations are hoisted as undefined.

3

Function declarations are hoisted as undefined; var declarations are hoisted with their values.

4

Neither is hoisted; the engine just reads them top to bottom during execution.

Why does [] + [] result in an empty string?

Select the correct answer

1

Each empty array is treated as the number zero, and adding zero to zero returns nothing.

2

The + operator on arrays merges their elements, and two empty arrays merge into nothing.

3

Arrays are converted to null, and concatenating null with null produces an empty string.

4

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

1

When you need a plain dictionary with no inherited prototype properties.

2

When you want to clone an object including all its inherited methods.

3

When you need an object that automatically freezes itself on creation.

4

When you want faster property lookups than a normal object literal.

Why does a Promise resolve before a setTimeout(0)?

Select the correct answer

1

Promise callbacks run as microtasks, which drain before any timer.

2

setTimeout enforces a minimum delay that Promise callbacks bypass.

3

Promise callbacks have higher thread priority than timer callbacks.

4

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

1

It automatically rejects with undefined once the event loop goes idle

2

It throws a timeout error after the default microtask queue empties out

3

It resolves to undefined as soon as all synchronous code finishes running

4

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

1

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

2

The DOM is the live tree, the Virtual DOM is an in-memory copy used for diffing, and the Shadow DOM scopes encapsulated subtrees

3

The DOM is rendered by the GPU, the Virtual DOM stores event listeners, and the Shadow DOM is a backup copy restored after reloads

4

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

1

It clones functions and DOM nodes along with data, producing an exact executable copy of any object

2

It deep-clones values including Date, Map, Set, and circular references that JSON cannot handle

3

It clones values faster by skipping nested objects, returning a shallow copy of only the top-level keys

4

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

1

ESM runs only in Node.js whereas CommonJS is the native module system shipped inside browsers

2

ESM is statically analyzable and async, enabling tree-shaking; CommonJS loads dynamically and synchronously

3

ESM and CommonJS behave identically, but ESM uses shorter keywords for the same dynamic loading

4

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

1

Short polling sends periodic requests; long polling keeps each request open until data is ready; WebSockets maintain a persistent bidirectional link.

2

Short polling holds requests open indefinitely; long polling fires fixed-interval requests; WebSockets poll the server only when data exists.

3

Short polling uses bidirectional sockets; long polling streams data continuously; WebSockets close immediately after each server response.

4

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

1

An iterable requires a Symbol.asyncIterator method, and the iterator returns promises resolving to plain final values.

2

An iterable defines a next() method directly, while an iterator wraps it in a Symbol.iterator returning indexes.

3

An iterable exposes a Symbol.iterator method returning an iterator whose next() yields { value, done } objects.

4

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

1

Scripts always run in parallel with HTML parsing and never block construction of the DOM or CSSOM trees.

2

CSS blocks script execution but scripts themselves never pause the parser or delay the very first paint.

3

JavaScript executes only after the page fully renders, so it can never affect parsing or the layout timing.

4

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

1

Synchronously within each microtask as soon as the related promise gets resolved

2

Immediately after every DOM mutation occurs, before any queued task can be run next

3

After the microtask queue empties between tasks, throttled to the display refresh rate

4

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

1

Reflow only redraws pixels and is cheaper; repaint reorders the entire DOM tree very slowly

2

Repaint rebuilds the render tree and is costlier; cache stored layout values to lower the cost

3

Repaint recalculates element positions and is costlier; avoid changing colors too frequently

4

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

1

Microtasks run fully after each task before the next macrotask; they take priority over macrotasks

2

Macrotasks like promises run first; microtasks like timers wait until the stack fully clears out

3

Microtasks and macrotasks alternate one by one; neither one has priority over the rendering step

4

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

1

The function frame stays on the stack while later code runs concurrently on another thread

2

The stack blocks and waits on that frame until the awaited promise resolves with a value

3

The function suspends and is popped off the stack; its rest resumes later as a microtask

4

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

1

The engine caps microtasks per cycle, so recursion simply defers any leftover callbacks to later loop iterations.

2

Recursive microtasks become macrotasks, letting rendering proceed normally between each scheduled callback execution.

3

Each microtask waits one full event-loop tick, so recursion just spreads the work across many frames safely.

4

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

1

Memory the engine allocates twice for one object, doubling heap usage whenever closures capture outer-scope variables.

2

Memory reserved by the engine for future allocations that closures and listeners permanently lock during their lifetime.

3

Memory no longer used but still referenced, so GC cannot free it; closures and listeners keep references alive.

4

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

1

It periodically copies all live objects into a new region, then erases the entire old region in one pass.

2

It marks all objects reachable from the roots, then sweeps and frees every object left unmarked.

3

It scans the stack for stale objects, then moves long-lived ones into a separate permanent heap region.

4

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

1

Optimized code is discarded and the engine reverts to slower code when object shapes or types change.

2

A function is permanently disabled after errors, and the engine recompiles the whole script on the next call.

3

Several hot functions are merged into one, which often slows execution when their argument types differ widely.

4

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

1

A function observing a target that fires callbacks after changes, commonly used for logging and debugging.

2

An object wrapping a target that uses traps to intercept operations, useful for validation and logging.

3

A wrapper that caches a target's properties for speed, often used to log access and validate cached values.

4

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

1

It compiles frequently executed bytecode into optimized machine code at runtime instead of interpreting it.

2

It translates the entire source file into machine code once before execution begins, like a static compiler.

3

It converts machine code back into bytecode whenever a function becomes hot, reducing the interpreter's workload.

4

It precompiles every function into native code during parsing, caching them on disk for faster future startups.

JavaScript Senior Quiz | TechPrep