JavaScript Expert

1 / 94

What is the difference between var, let, and const?

Select the correct answer

1

var and let are global-scoped; const is block-scoped and always reassignable.

2

var is block-scoped; let and const are function-scoped, and let can't be reassigned.

3

All three are block-scoped, but only const is hoisted to the top of its block.

4

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

1

Global covers a file; function scope covers blocks; block scope covers modules only.

2

Global is per module; function scope is global; block scope covers entire functions.

3

Global is per file; function scope is per block; block scope applies only to loops.

4

Global is accessible everywhere; function scope is per function; block scope is per {}.

What is variable shadowing?

Select the correct answer

1

A constant is reassigned and its previous value is hidden by the engine

2

A variable is referenced before its declaration is hoisted within the scope

3

A global variable is silently created when an assignment omits a keyword

4

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

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 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.

What is the difference between null and undefined? When would you intentionally use one over the other?

Select the correct answer

1

undefined is a deliberate empty value, while null means a missing variable

2

null and undefined are identical and both indicate a deleted object reference

3

null is reserved for numbers, while undefined applies to all object types

4

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

1

Both return "object"; null had a type tag of zero in early implementations

2

Arrays return "array" and null returns "null", reflecting their distinct value tags

3

Arrays return "object" and null returns "undefined" due to a parser limitation

4

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

1

string, number, boolean, null, object, symbol, array

2

string, number, boolean, object, array, function, date

3

string, number, float, boolean, undefined, symbol, bigint

4

string, number, boolean, null, undefined, symbol, bigint

Why does 0.1 + 0.2 not equal 0.3 in JavaScript?

Select the correct answer

1

JavaScript stores all numbers as integers, so the decimal fractions get truncated on addition

2

The addition operator rounds each operand to one digit before combining the two values

3

Floating-point math is performed in base ten but limited to fifteen significant digits total

4

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

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

What is type coercion, and why is === generally preferred over ==? Are there cases where == is actually useful?

Select the correct answer

1

=== coerces types and == does not, making == faster and safer for nearly all comparisons.

2

Neither coerces types, but === also compares object identity, so the two are equivalent.

3

== coerces types and === does not, but == null usefully checks both null and undefined.

4

Both compare identically, so === merely exists for backward compatibility with older code.

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.

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.

What is a higher-order function? Provide examples from the built-in Array.prototype.

Select the correct answer

1

A function defined at the top level of a module, such as parseInt, isNaN, and encodeURI.

2

A function that mutates the array it is called on in place, such as push, pop, and splice.

3

A function that accepts a function argument or returns one, such as map, filter, and reduce.

4

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

1

Arrow functions create a new this bound to whatever object invokes them at call time.

2

Arrow functions have no own this and inherit it from the enclosing lexical scope.

3

Both resolve this dynamically, but arrow functions can be rebound later with bind.

4

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

1

Both are hoisted identically, but only declarations can be assigned to a variable name.

2

A declaration is hoisted with its body, while an expression's name is not usable before definition.

3

An expression is hoisted with its body, while a declaration must be defined before it is called.

4

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

1

map transforms into a new array, forEach returns nothing, filter selects, reduce yields one value.

2

map mutates in place, forEach copies it, filter sorts, and reduce reverses the array.

3

map returns a value, forEach returns an array, filter counts, and reduce groups items.

4

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

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.

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.

What are the three states of a Promise?

Select the correct answer

1

Waiting, settled, and rejected.

2

Pending, fulfilled, and rejected.

3

Started, completed, and failed.

4

Pending, resolved, and cancelled.

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

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 does preventDefault() do, and how does it differ from stopPropagation()?

Select the correct answer

1

preventDefault cancels the browser's default action; stopPropagation stops the event from propagating further

2

preventDefault delays the default action briefly; stopPropagation prevents the event from being dispatched at all

3

preventDefault stops the event bubbling to parents; stopPropagation cancels the browser's default behavior entirely

4

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

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

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

How can you use closures to create private variables?

Select the correct answer

1

Declaring variables with the private keyword inside a function body to hide them

2

An outer function holds variables and returns inner functions that can access them

3

Marking variables as const so external code cannot read or reassign them

4

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

1

All values including primitives are passed as references to the original

2

Primitives are passed by reference while objects are passed by their value

3

All values including objects are deeply copied when passed into a function

4

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

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

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

What is the Nullish Coalescing operator (??) and how does it differ from the Logical OR operator?

Select the correct answer

1

?? returns the right side only when the left is null or undefined

2

|| returns the right side only when the left is null or undefined

3

?? returns the left side only when the right is null or undefined

4

?? 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

1

It returns undefined yet keeps evaluating the rest of the chain anyway

2

It returns undefined and stops evaluating when a reference is null or undefined

3

It returns null and stops evaluating when a reference is any falsy value at all

4

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

1

Both collect multiple arguments into a single array passed into the function

2

Both expand iterables into individual elements depending on where they are used

3

Spread expands an iterable into elements; rest collects arguments into one array

4

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

1

It unpacks array values by position and object values by matching property names

2

It copies entire arrays and objects into new variables without unpacking them

3

It merges multiple arrays and objects into one combined destination variable

4

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

1

for...in runs synchronously while for...of runs asynchronously over the iterator protocol

2

for...in iterates enumerable property keys; for...of iterates values of iterable objects

3

for...in iterates array values; for...of iterates only the numeric index keys of objects

4

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

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.

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.

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 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 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 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.

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.

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 Expert Quiz | TechPrep