JavaScript Mid

1 / 51

What is the Temporal Dead Zone (TDZ), and why can't let and const variables be accessed before their declaration even though they are hoisted?

Select the correct answer

1

They are hoisted but remain uninitialized until their declaration, so access throws.

2

They are stored in a separate scope that only loads after the function ends.

3

They are hoisted and initialized to undefined, but the engine blocks reads.

4

They are not hoisted at all, so the engine cannot locate them before declaration.

How does the JavaScript engine handle nested scopes when looking up a variable?

Select the correct answer

1

It searches the scope where the function was called, moving up the call stack.

2

It checks only the immediate parent scope and the global scope, nothing else.

3

It searches the current scope, then each outer scope up the chain until global.

4

It searches the global scope first, then narrows down into the inner scopes.

Why can you access a variable defined with var before its declaration, but not one defined with let?

Select the correct answer

1

var is initialized to undefined when hoisted, while let stays uninitialized in the TDZ.

2

var is not hoisted but reachable, while let is hoisted yet blocked from reads.

3

var is block-scoped and initialized early, while let is function-scoped and delayed.

4

var is stored globally on load, while let is created only when first assigned.

What are the tradeoffs of using global scope, and how do ES Modules help mitigate these issues?

Select the correct answer

1

Globals risk name collisions and pollution; ES Modules scope each file separately.

2

Globals improve performance; ES Modules slow access by isolating every variable.

3

Globals are always block-scoped; ES Modules convert them into function scope.

4

Globals prevent reuse of names; ES Modules expose everything to the window object.

What are 'truthy' and 'falsy' values? Why is [] == false true, but [] itself is truthy?

Select the correct answer

1

An empty array is falsy by definition, but the == operator treats every object as a truthy value

2

Both checks coerce to boolean, so [] is consistently falsy across loose equality and conditionals

3

The == operator compares array length to 0, while truthiness ignores the contents entirely

4

In ==, the array coerces to "" then 0, yet all objects are inherently truthy

What is NaN, and why is typeof NaN a 'number'?

Select the correct answer

1

It is an undefined symbol whose typeof defaults to number for legacy compatibility reasons

2

It is a failed numeric result and still belongs to the number type per the floating-point spec

3

It is a special empty string that JavaScript silently casts into the number type during math

4

It is a separate primitive type that typeof deliberately reports as number to avoid errors

What is a Symbol in JavaScript, and what are some practical use cases for it?

Select the correct answer

1

A unique immutable primitive used as non-colliding object keys and well-known protocols

2

A mutable wrapper object that enforces private fields and hides them from inheritance

3

A reference type holding a unique string label that can be reused across separate objects

4

A special numeric constant used to tag objects and enable faster property lookups

Explain implicit type coercion in JavaScript.

Select the correct answer

1

JavaScript requires the developer to explicitly convert types before any operation runs.

2

JavaScript throws a runtime error whenever two operands have differing primitive types.

3

JavaScript caches converted values so repeated operations skip type conversion entirely.

4

JavaScript automatically converts a value from one type to another during an operation.

What is the difference between Object.is() and the strict equality operator (===)?

Select the correct answer

1

Object.is treats NaN as unequal to NaN, while === treats +0 and -0 as distinct values.

2

Object.is considers NaN equal to NaN and treats +0 and -0 as different values.

3

Object.is performs type coercion first, whereas === compares the operands without coercion.

4

Object.is compares object references deeply, whereas === only compares them shallowly here.

How is the value of this determined in different contexts (e.g., arrow functions, regular functions, methods, and the new keyword)?

Select the correct answer

1

Methods bind this to the global object, while arrow functions each create a fresh this binding.

2

Arrow functions take this lexically; methods bind it to the object; new binds it to the instance.

3

Regular functions always bind this to the global object; arrow functions leave this undefined.

4

this is fixed lexically wherever a function is defined, independent of how it is later called.

Explain 'Function Currying' and why you might use it.

Select the correct answer

1

Combining several small functions into one large function that runs them in a fixed order.

2

Transforming a multi-argument function into a sequence of single-argument functions for reuse.

3

Caching a function's return values so repeated calls with the same input run much faster.

4

Delaying a function's execution until all of its arguments are gathered into one array call.

What is the difference between .call(), .apply(), and .bind()? When would you use one over the others?

Select the correct answer

1

call and apply invoke now (apply takes an args array); bind returns a new bound function.

2

All three invoke the function immediately; they differ only in how the arguments are passed in.

3

call and bind invoke now (call takes an args array); apply returns a new bound function later.

4

apply and bind invoke now (bind takes an args array); call returns a new bound function later.

What is an IIFE (Immediately Invoked Function Expression), and why was it commonly used?

Select the correct answer

1

A function run immediately on definition, used to create a private isolated scope.

2

A function declared globally, used to expose helpers shared across every script file.

3

A function cached after first call, used to memoize results across the whole module.

4

A function deferred until idle, used to delay heavy work after the page loads.

What is the difference between __proto__ and prototype?

Select the correct answer

1

prototype is a property on constructor functions; __proto__ is the actual link on an instance.

2

__proto__ is a property on constructor functions; prototype is the actual link on an instance.

3

prototype exists only on instances, while __proto__ exists only on classes and arrays.

4

Both refer to the same internal slot; __proto__ is just an older alias for prototype.

What is prototypal inheritance, and how does it differ from classical inheritance found in languages like Java or C++?

Select the correct answer

1

Inheritance is resolved at compile time using static class hierarchies and interfaces.

2

Classes are copied into each object at creation, so instances never share a live link.

3

Objects inherit directly from other objects through the prototype chain, not from classes.

4

Objects inherit only from rigid class blueprints defined ahead of time, like in Java.

Explain the prototype chain. What happens when you try to access a property that doesn't exist on an object?

Select the correct answer

1

JavaScript walks up the chain until found or reaching null, then throws a ReferenceError.

2

JavaScript searches the chain downward from Object, then returns null if missing.

3

JavaScript checks only the object itself, then immediately returns undefined without searching.

4

JavaScript walks up the chain until found or reaching null, then returns undefined.

What happens under the hood when you call a function with the new keyword?

Select the correct answer

1

An empty array is created, this is bound to it, and that array is returned to the caller.

2

The function runs in the global scope, this points to window, and a string is returned.

3

A clone of the function is created, its body is cached, and a copy of it is returned.

4

A new object is created, its prototype is linked, this is bound, and the object is returned.

Why are ES6 classes called syntactic sugar?

Select the correct answer

1

They add new private inheritance semantics not possible before.

2

They desugar to the existing prototype-based inheritance model.

3

They compile directly to optimized machine code at runtime.

4

They replace prototypes with a true classical inheritance system.

How does the instanceof operator work, and how does it relate to the prototype chain?

Select the correct answer

1

It checks whether a constructor's prototype exists in the object's prototype chain.

2

It compares the constructor functions of two objects for strict equality.

3

It verifies that an object was created with the new keyword directly.

4

It checks whether an object has a property defined by the constructor.

Why would you use async/await over raw Promises? Are there any performance trade-offs?

Select the correct answer

1

It improves readability with negligible runtime overhead over Promises.

2

It avoids the microtask queue, reducing scheduling overhead entirely.

3

It runs asynchronous code synchronously, blocking less than Promises.

4

It executes significantly faster than chained Promise callback functions.

What is the difference between Promise.all, Promise.allSettled, Promise.any, and Promise.race, and when would you choose one over the others?

Select the correct answer

1

all rejects on first rejection; allSettled resolves on first; any rejects if all fail; race waits for the slowest to settle.

2

all rejects on first rejection; allSettled never rejects; any resolves on first fulfillment; race settles on first settled.

3

all waits for all to settle; allSettled rejects on error; any settles on first settled; race resolves on first fulfillment.

4

all resolves on first fulfillment; allSettled rejects on first error; any waits for all; race ignores all rejections.

How does the fetch API handle HTTP error status codes like 404 or 500?

Select the correct answer

1

It throws a synchronous error before the Promise is returned.

2

It retries the request automatically until a 2xx status returns.

3

It resolves normally; the Promise only rejects on network failure.

4

It rejects the Promise automatically for any 4xx or 5xx status.

When would you use Promise.allSettled instead of Promise.all?

Select the correct answer

1

When you need every promise to finish regardless of individual rejections

2

When you only need the first promise that resolves successfully back

3

When you want to reject early as soon as any single promise rejects

4

When you must run all the promises strictly one after another in order

What are the different states of a Promise, and can a Promise be 'cancelled' in native JavaScript?

Select the correct answer

1

Created, running, done; native promises abort via AbortController

2

Waiting, success, failure; native promises expose a built-in cancel call

3

Pending, resolved, settled; native promises can be cancelled anytime

4

Pending, fulfilled, rejected; native promises cannot be cancelled

Why does await block the execution of a function but not the entire main thread?

Select the correct answer

1

It pauses the async function and yields control back to the event loop

2

It spawns a worker thread so the main thread stays fully responsive always

3

It blocks the call stack briefly while other timers keep running normally

4

It freezes the whole thread but lets the browser repaint in the background

How does error handling work with try/catch/finally, and how do you create custom error types?

Select the correct answer

1

finally runs only on success; clone Error to build custom error types

2

finally always runs; extend the Error class for custom error types

3

finally skips on return; wrap Error inside plain objects for custom types

4

catch always runs first; override Error to define custom error types

What is 'Event Delegation' and why is it considered a performance optimization?

Select the correct answer

1

Attaching a single listener on a parent to handle events from its children

2

Cloning event handlers across siblings so each one reacts independently fast

3

Attaching a listener to each child element and removing them after firing

4

Delegating event handling to a web worker to free up the main thread fully

Explain Event Bubbling and Event Capturing. How do you stop an event from propagating?

Select the correct answer

1

Capturing goes top-down, bubbling bottom-up; stopPropagation() stops it

2

Both phases run bottom-up; returning false from a handler stops it always

3

Bubbling goes top-down, capturing bottom-up; preventDefault() stops it

4

Capturing fires after bubbling ends; stopPropagation() cancels both phases

What is the difference between stopPropagation() and stopImmediatePropagation()?

Select the correct answer

1

stopImmediatePropagation() also blocks other listeners on the same element

2

stopPropagation() cancels capturing but keeps the bubbling phase going

3

stopImmediatePropagation() also prevents the element's default action

4

stopPropagation() also blocks all other listeners on the same element

What is the difference between an attribute and a property in the DOM?

Select the correct answer

1

Attributes always stay in sync with properties, since both reference the exact same underlying value held in memory

2

Attributes can hold any data type at runtime; properties are limited to strings parsed directly from the HTML source

3

Attributes are the initial values in the HTML markup as strings; properties are the current values on the DOM object

4

Attributes are the live values on the DOM object; properties are the static strings written once in the HTML markup

What is requestAnimationFrame, and how does it differ from setTimeout for animations?

Select the correct answer

1

It runs a callback on a separate worker thread, guaranteeing smooth frames regardless of the main thread load

2

It runs a callback exactly every 16 milliseconds, ignoring the monitor refresh rate and battery saving modes

3

It runs a callback before the next repaint, syncing with the refresh rate and pausing in hidden tabs

4

It runs a callback after a fixed delay in milliseconds, firing continuously even while the tab stays hidden

Explain closures and provide a real-world example of when you would use one.

Select the correct answer

1

A function that retains access to its outer scope's variables, useful for private state or data hiding

2

A function that copies its outer scope's variables by value, useful for freezing constants at definition time

3

A function bound permanently to one object, useful for ensuring this always refers to the same instance

4

A function that runs immediately and discards its scope, useful for avoiding global namespace pollution entirely

What is a 'Pure Function' and why are they preferred in many modern architectures?

Select the correct answer

1

It returns a new value each time it is called and mutates shared state, making it flexible and reusable

2

It returns the same output for the same input and has no side effects, making it predictable and testable

3

It always returns a Promise and never throws errors, making it safe to use in asynchronous pipelines

4

It accepts no arguments and reads only from global variables, making it simple and fast to execute

What is 'Memoization' and how does it relate to closures?

Select the correct answer

1

Limiting how often a function runs within a time window; a closure tracks the last execution time

2

Caching results by arguments so repeated calls skip recomputation; a closure holds the private cache

3

Storing a function's source code as a string for later eval; a closure compiles it on first call

4

Splitting a function into smaller steps run lazily; a closure schedules each step on the next tick

What does Object.freeze() do, and how can you achieve immutability in JavaScript?

Select the correct answer

1

It prevents reassigning the variable but still allows freely mutating its properties

2

It converts the object into a read-only string that cannot be parsed back later

3

It makes an object deeply immutable, recursively freezing every nested object inside it

4

It makes an object shallowly immutable, preventing adding, removing, or changing properties

How does JSON.stringify handle things like functions, undefined, and circular references, and what do the replacer and toJSON do?

Select the correct answer

1

Functions and undefined are omitted, circular references throw, and toJSON customizes output

2

Functions are kept as strings and undefined is omitted, and circular references throw

3

Functions become null and undefined stays, while circular references are skipped silently

4

Functions and undefined are serialized, and circular references are resolved into null

Explain the difference between shallow copy and deep copy, and when is structuredClone() preferred over JSON.parse(JSON.stringify())?

Select the correct answer

1

structuredClone() makes a shallow copy while JSON.parse(JSON.stringify()) always produces a deeper copy

2

structuredClone() runs faster but loses nested values that JSON reliably keeps in every case

3

structuredClone() preserves Dates, Maps and circular refs that JSON silently drops or breaks

4

structuredClone() copies functions and prototypes whereas JSON preserves the full class hierarchy

What is the difference between Map/Set and WeakMap/WeakSet, and why would you use a weak version for memory management?

Select the correct answer

1

Weak versions are iterable and ordered, freeing memory each time the loop completes a pass

2

Weak versions accept primitive keys and release them when the value field is set to null

3

Weak versions hold keys strongly but cap their total size to limit memory growth over time

4

Weak versions hold keys weakly, letting unreferenced entries be garbage collected automatically

What are the trade-offs of using a Map versus a plain Object for storing key-value pairs?

Select the correct answer

1

Map allows any key type, keeps insertion order, and exposes size for frequent additions and deletions

2

Map is always serialized by JSON.stringify() and outperforms objects for static fixed key sets

3

Map inherits from Object.prototype, so it shares the same prototype-pollution risks during lookups

4

Map coerces all keys to strings and uses .length to count entries faster than an object can

What are the trade-offs between Throttling and Debouncing? When would you use one over the other for a search input vs. a window resize event?

Select the correct answer

1

Both fire only once after the event ends, so either choice produces identical behavior in practice

2

Debounce runs the handler on every event while throttle delays it until the user stops interacting

3

Debounce fits search inputs by waiting until typing stops; throttle fits resize by capping firing rate

4

Throttle fits search inputs by waiting until typing stops; debounce fits resize by capping firing rate

Explain the concept of 'Tree Shaking' and how static import/export statements enable it.

Select the correct answer

1

Bundlers statically analyze import/export to detect and drop unused exports at build time

2

The runtime analyzes import/export calls to lazily load unused exports only when first referenced

3

Minifiers rename import/export bindings into short symbols so unused code shrinks but stays in the bundle

4

Browsers cache import/export modules and discard unused ones from memory after the page finishes loading

What are Generator functions, and how do they differ from standard functions in terms of execution control?

Select the correct answer

1

They execute their body eagerly when called and use yield only to log intermediate values during the run

2

They run fully asynchronously via yield, returning a promise that resolves once the function body completes

3

They restart from the top on every next() call, discarding any local state created in prior invocations

4

They can pause and resume execution via yield, returning an iterator that runs lazily on each call

What is 'Strict Mode' (use strict) and what specific errors does it prevent?

Select the correct answer

1

It automatically converts loose equality into strict equality and forces every variable to be block-scoped with let.

2

It speeds up code by enabling aggressive compiler optimizations and removing all runtime type checks for declared variables.

3

It enables newer syntax features such as classes and arrow functions that are otherwise disabled in legacy older browsers.

4

It enforces stricter parsing and throws errors for unsafe actions like assigning to undeclared variables or duplicate parameters.

What are private class fields (using the # prefix), and how do they differ from the convention of using underscores?

Select the correct answer

1

# fields create getters automatically while underscore properties require manually writing getter and setter methods.

2

# fields are syntactic sugar for underscore properties and remain fully accessible from any external code at runtime.

3

# fields and underscores both hide data, but underscores are checked by the engine while # is convention.

4

# fields are enforced by the engine and truly inaccessible outside the class, whereas underscores are only a naming convention.

What is Object.groupBy(), and how does it differ conceptually from using reduce for grouping?

Select the correct answer

1

Object.groupBy() mutates the original array in place, while reduce always returns a brand-new immutable grouped object.

2

Object.groupBy() sorts elements before grouping them, while reduce groups items without changing their original order.

3

Object.groupBy() returns a Map of grouped values, whereas reduce can only ever produce a single numeric accumulator.

4

Object.groupBy() groups array items into an object keyed by a callback's return value, doing declaratively what reduce builds manually.

Compare localStorage, sessionStorage, and Cookies. What are the security and storage-limit trade-offs of each?

Select the correct answer

1

localStorage persists with no expiry, sessionStorage clears per tab, and cookies are small and sent with every request.

2

All three share the same 5MB limit, but only cookies are accessible across the different browser tabs and separate windows.

3

sessionStorage persists across sessions, localStorage is per tab, and cookies are never transmitted to the remote server.

4

localStorage is sent with each request, sessionStorage persists forever, and cookies hold the largest amount of overall data.

What is the difference between a Web Worker and a Service Worker, and when would you use one over the other?

Select the correct answer

1

Web Worker offloads CPU work off the main thread; Service Worker proxies network for caching

2

Web Worker proxies network requests for offline use; Service Worker runs heavy computations

3

Web Worker handles push notifications only; Service Worker parses large JSON data synchronously

4

Web Worker shares the DOM across browser tabs; Service Worker runs background timers nonstop

Explain the JavaScript event loop and the relationship between the call stack, Web APIs, the callback queue, and the microtask queue.

Select the correct answer

1

Web APIs run on the stack while the loop pushes microtasks and macrotasks together each cycle

2

When the stack empties, the loop drains all microtasks, then runs one callback-queue macrotask

3

The callback queue runs before microtasks whenever the Web APIs finish a background operation

4

The loop runs one macrotask, then one microtask, alternating whether or not the stack is empty

Why does setTimeout with 0 milliseconds not necessarily execute in 0 milliseconds?

Select the correct answer

1

Zero is ignored entirely and the callback runs synchronously right after the current line

2

The browser rounds the supplied value up to the nearest full second before queueing it

3

The callback runs before microtasks but only after every other timer has already executed

4

The delay is a minimum; the callback waits for the stack to clear and the queue to reach it

How does the JavaScript event loop handle a single thread while performing non-blocking I/O?

Select the correct answer

1

I/O is offloaded to host APIs outside the main thread; callbacks queue and run when it is free

2

It blocks the single thread briefly per request but switches contexts fast enough to feel async

3

It spawns a new JavaScript thread per request so the main thread never has to wait on any I/O

4

It polls each I/O operation in a tight loop on the main thread until the data is fully ready

Explain the new Set methods in ES2025 (union, intersection, difference) and when you'd use them.

Select the correct answer

1

union mutates the first set in place, intersection returns a boolean, difference returns the symmetric difference.

2

union returns all elements of both sets, intersection the shared ones, difference those only in the first.

3

union returns shared elements only, intersection all elements, difference removes duplicates between two sets.

4

union merges and sorts both sets, intersection compares sizes, difference returns elements missing from both.

JavaScript Mid Quiz | TechPrep