JavaScript Expert
What is the difference between var, let, and const?
Select the correct answer
var and let are global-scoped; const is block-scoped and always reassignable.
var is block-scoped; let and const are function-scoped, and let can't be reassigned.
All three are block-scoped, but only const is hoisted to the top of its block.
var is function-scoped; let and const are block-scoped, and const can't be reassigned.
Explain the difference between Global Scope, Function Scope, and Block Scope.
Select the correct answer
Global covers a file; function scope covers blocks; block scope covers modules only.
Global is per module; function scope is global; block scope covers entire functions.
Global is per file; function scope is per block; block scope applies only to loops.
Global is accessible everywhere; function scope is per function; block scope is per {}.
What is variable shadowing?
Select the correct answer
A constant is reassigned and its previous value is hidden by the engine
A variable is referenced before its declaration is hoisted within the scope
A global variable is silently created when an assignment omits a keyword
An inner scope declares a variable with the same name as one in an outer scope
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
They are hoisted but remain uninitialized until their declaration, so access throws.
They are stored in a separate scope that only loads after the function ends.
They are hoisted and initialized to undefined, but the engine blocks reads.
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
It searches the scope where the function was called, moving up the call stack.
It checks only the immediate parent scope and the global scope, nothing else.
It searches the current scope, then each outer scope up the chain until global.
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
var is initialized to undefined when hoisted, while let stays uninitialized in the TDZ.
var is not hoisted but reachable, while let is hoisted yet blocked from reads.
var is block-scoped and initialized early, while let is function-scoped and delayed.
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
Globals risk name collisions and pollution; ES Modules scope each file separately.
Globals improve performance; ES Modules slow access by isolating every variable.
Globals are always block-scoped; ES Modules convert them into function scope.
Globals prevent reuse of names; ES Modules expose everything to the window object.
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.
What is the difference between null and undefined? When would you intentionally use one over the other?
Select the correct answer
undefined is a deliberate empty value, while null means a missing variable
null and undefined are identical and both indicate a deleted object reference
null is reserved for numbers, while undefined applies to all object types
null is an intentional absence of value, while undefined means not yet assigned
How does the typeof operator behave with null and arrays, and why is typeof null returning 'object' a historical bug?
Select the correct answer
Both return "object"; null had a type tag of zero in early implementations
Arrays return "array" and null returns "null", reflecting their distinct value tags
Arrays return "object" and null returns "undefined" due to a parser limitation
Both return "object" because null was deliberately defined as an empty object reference
What are the primitive data types in JavaScript?
Select the correct answer
string, number, boolean, null, object, symbol, array
string, number, boolean, object, array, function, date
string, number, float, boolean, undefined, symbol, bigint
string, number, boolean, null, undefined, symbol, bigint
Why does 0.1 + 0.2 not equal 0.3 in JavaScript?
Select the correct answer
JavaScript stores all numbers as integers, so the decimal fractions get truncated on addition
The addition operator rounds each operand to one digit before combining the two values
Floating-point math is performed in base ten but limited to fifteen significant digits total
These decimals cannot be represented exactly in binary floating-point, causing rounding error
What are 'truthy' and 'falsy' values? Why is [] == false true, but [] itself is truthy?
Select the correct answer
An empty array is falsy by definition, but the == operator treats every object as a truthy value
Both checks coerce to boolean, so [] is consistently falsy across loose equality and conditionals
The == operator compares array length to 0, while truthiness ignores the contents entirely
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
It is an undefined symbol whose typeof defaults to number for legacy compatibility reasons
It is a failed numeric result and still belongs to the number type per the floating-point spec
It is a special empty string that JavaScript silently casts into the number type during math
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
A unique immutable primitive used as non-colliding object keys and well-known protocols
A mutable wrapper object that enforces private fields and hides them from inheritance
A reference type holding a unique string label that can be reused across separate objects
A special numeric constant used to tag objects and enable faster property lookups
What is type coercion, and why is === generally preferred over ==? Are there cases where == is actually useful?
Select the correct answer
=== coerces types and == does not, making == faster and safer for nearly all comparisons.
Neither coerces types, but === also compares object identity, so the two are equivalent.
== coerces types and === does not, but == null usefully checks both null and undefined.
Both compare identically, so === merely exists for backward compatibility with older code.
Explain implicit type coercion in JavaScript.
Select the correct answer
JavaScript requires the developer to explicitly convert types before any operation runs.
JavaScript throws a runtime error whenever two operands have differing primitive types.
JavaScript caches converted values so repeated operations skip type conversion entirely.
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
Object.is treats NaN as unequal to NaN, while === treats +0 and -0 as distinct values.
Object.is considers NaN equal to NaN and treats +0 and -0 as different values.
Object.is performs type coercion first, whereas === compares the operands without coercion.
Object.is compares object references deeply, whereas === only compares them shallowly here.
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.
What is a higher-order function? Provide examples from the built-in Array.prototype.
Select the correct answer
A function defined at the top level of a module, such as parseInt, isNaN, and encodeURI.
A function that mutates the array it is called on in place, such as push, pop, and splice.
A function that accepts a function argument or returns one, such as map, filter, and reduce.
A function that runs faster because the engine optimizes it, like sort and join.
What is the difference between an arrow function and a regular function regarding this?
Select the correct answer
Arrow functions create a new this bound to whatever object invokes them at call time.
Arrow functions have no own this and inherit it from the enclosing lexical scope.
Both resolve this dynamically, but arrow functions can be rebound later with bind.
Regular functions inherit this lexically, while arrow functions resolve it dynamically.
What is the difference between a function declaration and a function expression?
Select the correct answer
Both are hoisted identically, but only declarations can be assigned to a variable name.
A declaration is hoisted with its body, while an expression's name is not usable before definition.
An expression is hoisted with its body, while a declaration must be defined before it is called.
Neither is hoisted, but expressions are evaluated earlier during the parsing phase.
What is the difference between map, forEach, filter, and reduce?
Select the correct answer
map transforms into a new array, forEach returns nothing, filter selects, reduce yields one value.
map mutates in place, forEach copies it, filter sorts, and reduce reverses the array.
map returns a value, forEach returns an array, filter counts, and reduce groups items.
map and forEach both return new arrays, while filter and reduce mutate the original.
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
Methods bind this to the global object, while arrow functions each create a fresh this binding.
Arrow functions take this lexically; methods bind it to the object; new binds it to the instance.
Regular functions always bind this to the global object; arrow functions leave this undefined.
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
Combining several small functions into one large function that runs them in a fixed order.
Transforming a multi-argument function into a sequence of single-argument functions for reuse.
Caching a function's return values so repeated calls with the same input run much faster.
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
call and apply invoke now (apply takes an args array); bind returns a new bound function.
All three invoke the function immediately; they differ only in how the arguments are passed in.
call and bind invoke now (call takes an args array); apply returns a new bound function later.
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
A function run immediately on definition, used to create a private isolated scope.
A function declared globally, used to expose helpers shared across every script file.
A function cached after first call, used to memoize results across the whole module.
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
prototype is a property on constructor functions; __proto__ is the actual link on an instance.
__proto__ is a property on constructor functions; prototype is the actual link on an instance.
prototype exists only on instances, while __proto__ exists only on classes and arrays.
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
Inheritance is resolved at compile time using static class hierarchies and interfaces.
Classes are copied into each object at creation, so instances never share a live link.
Objects inherit directly from other objects through the prototype chain, not from classes.
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
JavaScript walks up the chain until found or reaching null, then throws a ReferenceError.
JavaScript searches the chain downward from Object, then returns null if missing.
JavaScript checks only the object itself, then immediately returns undefined without searching.
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
An empty array is created, this is bound to it, and that array is returned to the caller.
The function runs in the global scope, this points to window, and a string is returned.
A clone of the function is created, its body is cached, and a copy of it is returned.
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
They add new private inheritance semantics not possible before.
They desugar to the existing prototype-based inheritance model.
They compile directly to optimized machine code at runtime.
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
It checks whether a constructor's prototype exists in the object's prototype chain.
It compares the constructor functions of two objects for strict equality.
It verifies that an object was created with the new keyword directly.
It checks whether an object has a property defined by the constructor.
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.
What are the three states of a Promise?
Select the correct answer
Waiting, settled, and rejected.
Pending, fulfilled, and rejected.
Started, completed, and failed.
Pending, resolved, and cancelled.
Why would you use async/await over raw Promises? Are there any performance trade-offs?
Select the correct answer
It improves readability with negligible runtime overhead over Promises.
It avoids the microtask queue, reducing scheduling overhead entirely.
It runs asynchronous code synchronously, blocking less than Promises.
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
all rejects on first rejection; allSettled resolves on first; any rejects if all fail; race waits for the slowest to settle.
all rejects on first rejection; allSettled never rejects; any resolves on first fulfillment; race settles on first settled.
all waits for all to settle; allSettled rejects on error; any settles on first settled; race resolves on first fulfillment.
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
It throws a synchronous error before the Promise is returned.
It retries the request automatically until a 2xx status returns.
It resolves normally; the Promise only rejects on network failure.
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
When you need every promise to finish regardless of individual rejections
When you only need the first promise that resolves successfully back
When you want to reject early as soon as any single promise rejects
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
Created, running, done; native promises abort via AbortController
Waiting, success, failure; native promises expose a built-in cancel call
Pending, resolved, settled; native promises can be cancelled anytime
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
It pauses the async function and yields control back to the event loop
It spawns a worker thread so the main thread stays fully responsive always
It blocks the call stack briefly while other timers keep running normally
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
finally runs only on success; clone Error to build custom error types
finally always runs; extend the Error class for custom error types
finally skips on return; wrap Error inside plain objects for custom types
catch always runs first; override Error to define custom error types
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 does preventDefault() do, and how does it differ from stopPropagation()?
Select the correct answer
preventDefault cancels the browser's default action; stopPropagation stops the event from propagating further
preventDefault delays the default action briefly; stopPropagation prevents the event from being dispatched at all
preventDefault stops the event bubbling to parents; stopPropagation cancels the browser's default behavior entirely
preventDefault removes all listeners on the element; stopPropagation pauses the event loop until the handler returns
What is 'Event Delegation' and why is it considered a performance optimization?
Select the correct answer
Attaching a single listener on a parent to handle events from its children
Cloning event handlers across siblings so each one reacts independently fast
Attaching a listener to each child element and removing them after firing
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
Capturing goes top-down, bubbling bottom-up; stopPropagation() stops it
Both phases run bottom-up; returning false from a handler stops it always
Bubbling goes top-down, capturing bottom-up; preventDefault() stops it
Capturing fires after bubbling ends; stopPropagation() cancels both phases
What is the difference between stopPropagation() and stopImmediatePropagation()?
Select the correct answer
stopImmediatePropagation() also blocks other listeners on the same element
stopPropagation() cancels capturing but keeps the bubbling phase going
stopImmediatePropagation() also prevents the element's default action
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
Attributes always stay in sync with properties, since both reference the exact same underlying value held in memory
Attributes can hold any data type at runtime; properties are limited to strings parsed directly from the HTML source
Attributes are the initial values in the HTML markup as strings; properties are the current values on the DOM object
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
It runs a callback on a separate worker thread, guaranteeing smooth frames regardless of the main thread load
It runs a callback exactly every 16 milliseconds, ignoring the monitor refresh rate and battery saving modes
It runs a callback before the next repaint, syncing with the refresh rate and pausing in hidden tabs
It runs a callback after a fixed delay in milliseconds, firing continuously even while the tab stays hidden
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
How can you use closures to create private variables?
Select the correct answer
Declaring variables with the private keyword inside a function body to hide them
An outer function holds variables and returns inner functions that can access them
Marking variables as const so external code cannot read or reassign them
Using the # prefix on variables declared at the top level of a module
Explain the difference between passing by value and passing by reference in JavaScript.
Select the correct answer
All values including primitives are passed as references to the original
Primitives are passed by reference while objects are passed by their value
All values including objects are deeply copied when passed into a function
Primitives are passed by value while objects are passed by their reference
Explain closures and provide a real-world example of when you would use one.
Select the correct answer
A function that retains access to its outer scope's variables, useful for private state or data hiding
A function that copies its outer scope's variables by value, useful for freezing constants at definition time
A function bound permanently to one object, useful for ensuring this always refers to the same instance
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
It returns a new value each time it is called and mutates shared state, making it flexible and reusable
It returns the same output for the same input and has no side effects, making it predictable and testable
It always returns a Promise and never throws errors, making it safe to use in asynchronous pipelines
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
Limiting how often a function runs within a time window; a closure tracks the last execution time
Caching results by arguments so repeated calls skip recomputation; a closure holds the private cache
Storing a function's source code as a string for later eval; a closure compiles it on first call
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
It prevents reassigning the variable but still allows freely mutating its properties
It converts the object into a read-only string that cannot be parsed back later
It makes an object deeply immutable, recursively freezing every nested object inside it
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
Functions and undefined are omitted, circular references throw, and toJSON customizes output
Functions are kept as strings and undefined is omitted, and circular references throw
Functions become null and undefined stays, while circular references are skipped silently
Functions and undefined are serialized, and circular references are resolved into null
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
What is the Nullish Coalescing operator (??) and how does it differ from the Logical OR operator?
Select the correct answer
?? returns the right side only when the left is null or undefined
|| returns the right side only when the left is null or undefined
?? returns the left side only when the right is null or undefined
?? returns the right side whenever the left is any falsy value such as 0
What is 'Optional Chaining' (?.) and where does it short-circuit?
Select the correct answer
It returns undefined yet keeps evaluating the rest of the chain anyway
It returns undefined and stops evaluating when a reference is null or undefined
It returns null and stops evaluating when a reference is any falsy value at all
It throws an error but stops evaluating when a reference is null or undefined
What is the difference between the spread operator and rest parameters, and how are they used?
Select the correct answer
Both collect multiple arguments into a single array passed into the function
Both expand iterables into individual elements depending on where they are used
Spread expands an iterable into elements; rest collects arguments into one array
Rest expands an iterable into elements; spread collects arguments into one array
What is destructuring assignment, and how does it work for objects and arrays?
Select the correct answer
It unpacks array values by position and object values by matching property names
It copies entire arrays and objects into new variables without unpacking them
It merges multiple arrays and objects into one combined destination variable
It unpacks array values by property name and object values by their position
What is the difference between for...in and for...of loops?
Select the correct answer
for...in runs synchronously while for...of runs asynchronously over the iterator protocol
for...in iterates enumerable property keys; for...of iterates values of iterable objects
for...in iterates array values; for...of iterates only the numeric index keys of objects
for...in works on iterables only; for...of works on any plain object with enumerable keys
Explain the difference between shallow copy and deep copy, and when is structuredClone() preferred over JSON.parse(JSON.stringify())?
Select the correct answer
structuredClone() makes a shallow copy while JSON.parse(JSON.stringify()) always produces a deeper copy
structuredClone() runs faster but loses nested values that JSON reliably keeps in every case
structuredClone() preserves Dates, Maps and circular refs that JSON silently drops or breaks
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
Weak versions are iterable and ordered, freeing memory each time the loop completes a pass
Weak versions accept primitive keys and release them when the value field is set to null
Weak versions hold keys strongly but cap their total size to limit memory growth over time
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
Map allows any key type, keeps insertion order, and exposes size for frequent additions and deletions
Map is always serialized by JSON.stringify() and outperforms objects for static fixed key sets
Map inherits from Object.prototype, so it shares the same prototype-pollution risks during lookups
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
Both fire only once after the event ends, so either choice produces identical behavior in practice
Debounce runs the handler on every event while throttle delays it until the user stops interacting
Debounce fits search inputs by waiting until typing stops; throttle fits resize by capping firing rate
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
Bundlers statically analyze import/export to detect and drop unused exports at build time
The runtime analyzes import/export calls to lazily load unused exports only when first referenced
Minifiers rename import/export bindings into short symbols so unused code shrinks but stays in the bundle
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
They execute their body eagerly when called and use yield only to log intermediate values during the run
They run fully asynchronously via yield, returning a promise that resolves once the function body completes
They restart from the top on every next() call, discarding any local state created in prior invocations
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
It automatically converts loose equality into strict equality and forces every variable to be block-scoped with let.
It speeds up code by enabling aggressive compiler optimizations and removing all runtime type checks for declared variables.
It enables newer syntax features such as classes and arrow functions that are otherwise disabled in legacy older browsers.
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
# fields create getters automatically while underscore properties require manually writing getter and setter methods.
# fields are syntactic sugar for underscore properties and remain fully accessible from any external code at runtime.
# fields and underscores both hide data, but underscores are checked by the engine while # is convention.
# 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
Object.groupBy() mutates the original array in place, while reduce always returns a brand-new immutable grouped object.
Object.groupBy() sorts elements before grouping them, while reduce groups items without changing their original order.
Object.groupBy() returns a Map of grouped values, whereas reduce can only ever produce a single numeric accumulator.
Object.groupBy() groups array items into an object keyed by a callback's return value, doing declaratively what reduce builds manually.
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.
Compare localStorage, sessionStorage, and Cookies. What are the security and storage-limit trade-offs of each?
Select the correct answer
localStorage persists with no expiry, sessionStorage clears per tab, and cookies are small and sent with every request.
All three share the same 5MB limit, but only cookies are accessible across the different browser tabs and separate windows.
sessionStorage persists across sessions, localStorage is per tab, and cookies are never transmitted to the remote server.
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
Web Worker offloads CPU work off the main thread; Service Worker proxies network for caching
Web Worker proxies network requests for offline use; Service Worker runs heavy computations
Web Worker handles push notifications only; Service Worker parses large JSON data synchronously
Web Worker shares the DOM across browser tabs; Service Worker runs background timers nonstop
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 JavaScript event loop and the relationship between the call stack, Web APIs, the callback queue, and the microtask queue.
Select the correct answer
Web APIs run on the stack while the loop pushes microtasks and macrotasks together each cycle
When the stack empties, the loop drains all microtasks, then runs one callback-queue macrotask
The callback queue runs before microtasks whenever the Web APIs finish a background operation
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
Zero is ignored entirely and the callback runs synchronously right after the current line
The browser rounds the supplied value up to the nearest full second before queueing it
The callback runs before microtasks but only after every other timer has already executed
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
I/O is offloaded to host APIs outside the main thread; callbacks queue and run when it is free
It blocks the single thread briefly per request but switches contexts fast enough to feel async
It spawns a new JavaScript thread per request so the main thread never has to wait on any I/O
It polls each I/O operation in a tight loop on the main thread until the data is fully ready
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.
Explain the new Set methods in ES2025 (union, intersection, difference) and when you'd use them.
Select the correct answer
union mutates the first set in place, intersection returns a boolean, difference returns the symmetric difference.
union returns all elements of both sets, intersection the shared ones, difference those only in the first.
union returns shared elements only, intersection all elements, difference removes duplicates between two sets.
union merges and sorts both sets, intersection compares sizes, difference returns elements missing from both.
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.