JavaScript MCQ
Test your JavaScript knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
Which keyword declares a block-scoped variable in modern JavaScript?
Correct Answer
let
Explanation
let declares a block-scoped variable. const is also block-scoped but cannot be reassigned. var is function-scoped and hoisted.
2
What does typeof null return in JavaScript?
Correct Answer
"object"
Explanation
typeof null returns "object" — a historical bug in JavaScript that persists for backward compatibility.
3
What is the output of 0.1 + 0.2 === 0.3 in JavaScript?
Correct Answer
false
Explanation
Floating-point arithmetic: 0.1 + 0.2 = 0.30000000000000004. Use Math.abs(result - 0.3) < Number.EPSILON for comparison.
4
What does === check in JavaScript?
Correct Answer
Value and type equality without coercion
Explanation
=== (strict equality) checks both value and type without coercion. 1 === "1" is false. == uses type coercion.
5
What is a closure in JavaScript?
Correct Answer
A function that remembers and has access to variables from its outer scope even after the outer function has returned
Explanation
Closures capture variables from enclosing scopes. function counter() { let n=0; return () => n++; } — the inner function closes over n.
6
What does the spread operator ... do?
Correct Answer
Expands an iterable into individual elements
Explanation
[...arr1, ...arr2] merges arrays. f(...args) passes array elements as arguments. {...obj, key: val} creates a new object with spread properties.
7
What is event bubbling?
Correct Answer
An event propagating from the target element up through its ancestors in the DOM
Explanation
When you click a button, the click event bubbles up from the button to its parent, grandparent, and so on. Call event.stopPropagation() to prevent bubbling.
8
What does Array.prototype.map() return?
Correct Answer
A new array with each element transformed by the callback
Explanation
map() creates a new array. [1,2,3].map(x => x*2) returns [2,4,6]. The original array is not modified.
9
What is hoisting in JavaScript?
Correct Answer
Declarations being moved to the top of their scope by the JavaScript engine before execution
Explanation
var declarations and function declarations are hoisted. var is initialized to undefined; function declarations are fully hoisted. let/const are hoisted but not initialized (TDZ).
10
What is the Temporal Dead Zone (TDZ)?
Correct Answer
The period between entering a scope and the let/const declaration being initialized, during which accessing the variable throws ReferenceError
Explanation
let x; console.log(x) is fine, but console.log(x) before let x = 5 throws ReferenceError due to TDZ.
11
What is a Promise in JavaScript?
Correct Answer
An object representing the eventual completion or failure of an asynchronous operation
Explanation
Promises have three states: pending, fulfilled, and rejected. Chain with .then() and .catch(). Use async/await for cleaner syntax.
12
What is the difference between null and undefined?
Correct Answer
undefined means a variable is declared but not assigned; null is an intentional absence of value
Explanation
JavaScript sets uninitialized variables to undefined. null is explicitly assigned to represent "no value." typeof undefined === "undefined"; typeof null === "object".
13
What does Array.prototype.filter() return?
Correct Answer
A new array containing only elements for which the callback returns true
Explanation
[1,2,3,4].filter(x => x % 2 === 0) returns [2,4]. The original array is unchanged.
14
What is the this keyword in a regular function vs arrow function?
Correct Answer
In regular functions, this is dynamic (call-site determined). In arrow functions, this is lexically bound to the enclosing scope
Explanation
Arrow functions don't have their own this. They capture this from the surrounding context, which avoids the classic callback this-binding problem.
15
What does JSON.stringify() do?
Correct Answer
Converts a JavaScript value to a JSON string
Explanation
JSON.stringify({ a: 1 }) returns '{"a":1}'. JSON.parse() does the reverse. Functions and undefined values are omitted.
16
What is the prototype chain?
Correct Answer
The mechanism by which objects inherit properties and methods from other objects via the __proto__ / prototype link
Explanation
When accessing a property, JS searches the object, then its prototype, then the prototype's prototype, up to null. This chain enables inheritance.
17
What does the Array.prototype.reduce() method do?
Correct Answer
Reduces an array to a single value by applying a callback cumulatively
Explanation
[1,2,3].reduce((acc, x) => acc + x, 0) returns 6. The second argument is the initial accumulator value.
18
What is an Immediately Invoked Function Expression (IIFE)?
Correct Answer
A function defined and called immediately, creating an isolated scope
Explanation
(function() { /* code */ })() or (() => { /* code */ })() executes immediately. Used to avoid polluting global scope.
19
What is event.preventDefault() used for?
Correct Answer
Prevents the default browser behavior for an event (e.g., stopping a form submit or link navigation)
Explanation
event.preventDefault() stops default actions like form submission or anchor navigation while still allowing the custom handler to run.
20
What is NaN in JavaScript?
Correct Answer
Not a Number — a numeric value indicating an invalid arithmetic result
Explanation
NaN is of type "number" but represents invalid computations like 0/0 or parseInt("abc"). Use Number.isNaN() to check (typeof does not work reliably).
21
What does the typeof operator return for a function?
Correct Answer
"function"
Explanation
typeof function(){} returns "function". Functions are objects in JS but have a special typeof value.
22
What is destructuring in JavaScript?
Correct Answer
Unpacking values from arrays or properties from objects into distinct variables
Explanation
const { name, age } = user; or const [a, b] = arr; unpack values concisely.
23
What does Array.prototype.find() return?
Correct Answer
The first element for which the callback returns true, or undefined
Explanation
[5, 12, 8].find(x => x > 10) returns 12. findIndex() returns the index. filter() returns all matches.
24
What is the difference between for...of and for...in?
Correct Answer
for...of iterates values of iterables; for...in iterates enumerable property keys of objects
Explanation
for (const v of [1,2,3]) gives values 1,2,3. for (const k in {a:1}) gives key "a". Avoid for...in on arrays due to inherited properties.
25
What is a template literal?
Correct Answer
A backtick string supporting multi-line text and ${expression} interpolation
Explanation
`Hello, ${name}! You are ${age} years old.` is a template literal. They support multi-line and tagged template literals.
26
What does the optional chaining operator ?. do?
Correct Answer
Accesses nested properties safely, returning undefined if any part of the chain is null/undefined
Explanation
user?.address?.city returns undefined (not TypeError) if user or address is null/undefined.
27
What is the difference between == and ===?
Correct Answer
== performs type coercion before comparing; === compares type and value without coercion
Explanation
1 == "1" is true (coercion); 1 === "1" is false. Always prefer === to avoid surprising coercion results.
28
What does Object.keys() return?
Correct Answer
An array of the object's own enumerable property names
Explanation
Object.keys({ a:1, b:2 }) returns ["a", "b"]. Object.values() returns [1,2]. Object.entries() returns [["a",1],["b",2]].
29
What is a Set in JavaScript?
Correct Answer
A collection of unique values of any type
Explanation
new Set([1,2,2,3]) stores {1,2,3}. Sets support .add(), .has(), .delete(), .size, and are iterable.
30
What is a Map in JavaScript?
Correct Answer
A collection of key-value pairs where keys can be any type
Explanation
Map supports any key type (including objects), maintains insertion order, and has methods .get(), .set(), .has(), .delete().
31
What does async/await do?
Correct Answer
Pauses execution at await until a Promise resolves, enabling async code in a synchronous style
Explanation
async function f() { const result = await fetchData(); } pauses at await without blocking the thread.
32
What does Array.isArray() do?
Correct Answer
Returns true if the argument is an array
Explanation
Array.isArray([]) returns true. typeof [] returns "object", so Array.isArray() is the reliable way to check for arrays.
33
What is the ternary operator?
Correct Answer
condition ? valueIfTrue : valueIfFalse — a one-line conditional expression
Explanation
const label = age >= 18 ? "adult" : "minor"; is a concise alternative to if/else.
34
What is the difference between let, const, and var?
Correct Answer
var is function-scoped and hoisted; let is block-scoped and reassignable; const is block-scoped and not reassignable
Explanation
const prevents reassignment (not mutation). let and const are block-scoped with TDZ. var is function-scoped and should be avoided.
35
What does String.prototype.split() return?
Correct Answer
An array of substrings split at the specified delimiter
Explanation
"a,b,c".split(",") returns ["a","b","c"]. split("") returns an array of individual characters.
36
What is the purpose of the new keyword?
Correct Answer
Calls a constructor function, creates a new object, sets prototype, and returns the object
Explanation
new MyClass() creates an object, sets its __proto__ to MyClass.prototype, calls the constructor, and returns the new object.
37
What is the event loop?
Correct Answer
The mechanism that allows JavaScript to perform non-blocking operations by queuing callbacks and executing them when the call stack is empty
Explanation
JavaScript is single-threaded. The event loop picks tasks from the queue (macrotasks, microtasks) and executes them when the call stack is empty.
38
What does Object.assign() do?
Correct Answer
Copies own enumerable properties from source objects to a target object
Explanation
Object.assign({}, obj1, obj2) creates a shallow merge. It mutates and returns the target object.
39
What is a Symbol in JavaScript?
Correct Answer
A primitive value that is always unique, used to create unique property keys
Explanation
const sym = Symbol("desc"); creates a unique value. Symbol("a") !== Symbol("a"). Used for unique object property keys and protocol methods like Symbol.iterator.
40
What does Array.prototype.some() return?
Correct Answer
true if at least one element satisfies the callback condition
Explanation
[1,2,3].some(x => x > 2) returns true. every() checks all elements. some() short-circuits on first match.
1
What is the difference between microtasks and macrotasks?
Correct Answer
Microtasks (Promise callbacks, queueMicrotask) run before the next macrotask (setTimeout, setInterval, I/O callbacks)
Explanation
After each macrotask, the entire microtask queue drains before the next macrotask runs. This means Promise .then() callbacks run before setTimeout callbacks.
2
What is the WeakMap?
Correct Answer
A Map keyed by objects with weak references — entries are garbage collected when the key object has no other references
Explanation
WeakMap keys must be objects. When the object is collected, the entry is removed automatically. WeakMap is not enumerable.
3
What is a generator function?
Correct Answer
A function using function* and yield that produces a sequence of values lazily via an iterator
Explanation
function* gen() { yield 1; yield 2; } creates an iterator. Call gen().next() to get { value: 1, done: false }.
4
What is currying in JavaScript?
Correct Answer
Transforming a function with multiple arguments into a sequence of functions, each taking one argument
Explanation
const add = a => b => a + b; add(2)(3) returns 5. Currying enables partial application and functional composition.
5
What does Object.freeze() do?
Correct Answer
Makes an object immutable — no properties can be added, removed, or modified
Explanation
Object.freeze(obj) prevents mutation in strict mode (silently fails in non-strict). It is shallow — nested objects can still be mutated.
6
What is the difference between call(), apply(), and bind()?
Correct Answer
call() invokes immediately with individual args; apply() invokes immediately with args array; bind() returns a new function with this fixed
Explanation
f.call(ctx, a, b), f.apply(ctx, [a, b]) invoke f with ctx as this. f.bind(ctx, a) returns a new function with this permanently set.
7
What is prototype-based inheritance in JavaScript?
Correct Answer
Objects inherit directly from other objects via prototype links, not class blueprints
Explanation
JS uses prototypal inheritance. ES6 classes are syntactic sugar over prototype chains. Object.create(proto) creates an object with proto as its prototype.
8
What is memoization?
Correct Answer
Caching a function's result for given inputs so repeated calls with the same inputs return the cached result
Explanation
Memoization trades memory for speed. const memo = {}; if (memo[n]) return memo[n]; ... memo[n] = result; return result;
9
What are Proxy and Reflect in ES6?
Correct Answer
Proxy intercepts operations on objects via traps; Reflect provides methods that correspond to the interceptable operations
Explanation
new Proxy(target, { get(t, k) { return Reflect.get(t, k); } }) intercepts property reads. Used for validation, logging, and reactive state.
10
What is the difference between shallow and deep copy in JavaScript?
Correct Answer
Shallow copy copies only the top-level properties by reference; deep copy recursively copies all nested objects
Explanation
const shallow = { ...obj } shares nested object references. Deep copy: structuredClone(obj) (modern) or JSON.parse(JSON.stringify(obj)) (limited).
11
What does Promise.all() do?
Correct Answer
Resolves when all input Promises resolve; rejects immediately if any rejects
Explanation
Promise.all([p1, p2, p3]) resolves with an array of results. If any promise rejects, the whole thing rejects. Use Promise.allSettled for no-fail behavior.
12
What is the difference between Promise.race() and Promise.any()?
Correct Answer
race() settles (resolves or rejects) with the first settled Promise; any() resolves with the first resolved Promise and only rejects if all reject
Explanation
race() is first-settled (could be a rejection). any() ignores rejections and resolves with the first success, rejecting with AggregateError if all fail.
13
What is the module pattern in JavaScript?
Correct Answer
Using an IIFE or ES modules to encapsulate code and expose only a public API, hiding private state
Explanation
The module pattern uses closures to create private state. ES6 modules (import/export) provide built-in module support.
14
What is a Symbol.iterator used for?
Correct Answer
Making an object iterable by defining how for...of and spread iterate over it
Explanation
Implementing [Symbol.iterator]() on an object allows it to be used in for...of loops, spread, and destructuring.
15
What does structuredClone() do?
Correct Answer
Creates a deep clone of an object, supporting more types than JSON serialization
Explanation
structuredClone() deep-copies objects including Date, Map, Set, ArrayBuffer, and circular references — unlike JSON.parse(JSON.stringify()).
16
What is the purpose of WeakRef?
Correct Answer
Holds a weak reference to an object, not preventing garbage collection, with .deref() to access the object if still alive
Explanation
WeakRef allows checking if an object is still alive without preventing GC. Call .deref() — it returns the object or undefined if collected.
17
What is the Nullish Coalescing operator ??
Correct Answer
Returns the left operand unless it is null or undefined, in which case returns the right
Explanation
const name = user.name ?? "Anonymous"; only falls back for null/undefined, not 0 or "" (unlike ||). Use ??= for assignment: x ??= default.
18
What is the difference between Object.create(null) and {}?
Correct Answer
Object.create(null) creates an object with no prototype at all; {} has Object.prototype in its chain
Explanation
Object.create(null) is a truly empty object with no inherited methods like hasOwnProperty, toString. Useful for safe dictionaries with no prototype interference.
19
What is tagged template literals?
Correct Answer
A function called with a template literal, receiving the string parts and interpolated values as separate arguments
Explanation
sql`SELECT * FROM users WHERE id = ${id}` calls sql(strings, id). Used by styled-components, graphql-tag, and SQL query builders.
20
What is the purpose of FinalizationRegistry?
Correct Answer
Running a callback when a registered object is garbage collected, for cleanup of associated resources
Explanation
const registry = new FinalizationRegistry(value => { /* cleanup */ }); registry.register(obj, heldValue); fires callback when obj is GC'd.
21
What is the difference between Array.prototype.forEach() and for...of?
Correct Answer
for...of supports break/continue and works with any iterable; forEach cannot be broken and only works on arrays
Explanation
for...of loops can be exited with break or return, and work with any iterable (Set, Map, generator). forEach cannot be interrupted without throwing.
22
What is the difference between Array.from() and Array.of()?
Correct Answer
Array.from() creates an array from an iterable or array-like object; Array.of() creates an array from its arguments without the length-coercion of new Array()
Explanation
Array.from("abc") = ["a","b","c"]. Array.of(3) = [3] (not [undefined, undefined, undefined] like new Array(3)).
23
What is async iteration (for await...of)?
Correct Answer
A loop for consuming async iterables that yield promises, processing each value as it resolves
Explanation
for await (const chunk of stream) processes a ReadableStream. Async iterables implement [Symbol.asyncIterator](). Used with streams, paginated APIs.
24
What is the purpose of Object.entries() and how is it commonly used?
Correct Answer
Returns an array of [key, value] pairs for own enumerable properties, useful for iteration and conversion
Explanation
Object.entries(obj).map(([k, v]) => [k, transform(v)]) then Object.fromEntries(...) is a common pattern for transforming object values.
25
What is a JavaScript Proxy handler's set trap used for?
Correct Answer
Intercepting property assignment to add validation, logging, or transformation
Explanation
new Proxy({}, { set(t, k, v) { if (typeof v !== "number") throw TypeError(); return Reflect.set(t, k, v); } }) validates all assignments.
26
What is the difference between Object.keys() and Reflect.ownKeys()?
Correct Answer
Object.keys() returns own enumerable string keys; Reflect.ownKeys() returns all own keys including non-enumerable and Symbols
Explanation
Reflect.ownKeys(obj) = Object.getOwnPropertyNames(obj) + Object.getOwnPropertySymbols(obj). Complete low-level key introspection.
27
What is a JavaScript realm and its security implication?
Correct Answer
Each realm has its own global object and builtins; cross-realm instanceof checks fail, requiring Array.isArray() and structuredClone() workarounds
Explanation
An iframe in the same origin has a different realm. obj instanceof Array fails for arrays created in the iframe. Use Array.isArray() for cross-realm safety.
28
What is the Error.cause property (ES2022)?
Correct Answer
An optional property on Error for linking a new error to the original error, preserving the error chain
Explanation
throw new Error("fetch failed", { cause: originalError }) links errors. Access via err.cause, enabling better debugging of wrapped errors.
29
What is logical assignment (&&=, ||=, ??=) in JavaScript?
Correct Answer
Combined logical and assignment operators that only assign when the logical condition is met
Explanation
a ||= b assigns b to a only if a is falsy. a ??= b assigns if a is null/undefined. a &&= b assigns if a is truthy.
30
What is Array.prototype.at() and why was it added?
Correct Answer
Returns the element at a given index, supporting negative indices for end-of-array access without .length arithmetic
Explanation
arr.at(-1) returns the last element. arr[arr.length-1] is equivalent but verbose. Also works on strings and TypedArrays.
31
What is the hasOwn() method (ES2022)?
Correct Answer
A static method Object.hasOwn(obj, key) that checks for own property existence, safer than hasOwnProperty()
Explanation
Object.hasOwn(obj, "key") is equivalent to Object.prototype.hasOwnProperty.call(obj, "key") but works correctly on objects with no prototype (Object.create(null)).
32
What is the structuredClone() limitation with functions?
Correct Answer
Functions, DOM nodes, and class instances with methods cannot be structured-cloned; they throw DataCloneError
Explanation
The Structured Clone Algorithm cannot clone functions. Attempting to clone { fn: () => {} } throws DataCloneError. Plain data objects and most builtins work.
33
What is the difference between Symbol.toPrimitive and valueOf?
Correct Answer
Symbol.toPrimitive receives a hint ("number", "string", "default") for context-specific conversion; valueOf is called for numeric hints without hint info
Explanation
[Symbol.toPrimitive](hint) { if (hint === "string") return "text"; return 42; } provides full control over coercion in different contexts.
34
What is the temporal proposal (TC39 Stage 3) for JavaScript date handling?
Correct Answer
A new date/time API (Temporal.PlainDate, ZonedDateTime) fixing limitations of the legacy Date object (mutability, timezone handling)
Explanation
Temporal provides immutable, timezone-correct date-time types, fixing problems with Date: timezone handling, month numbering, and mutability.
35
What is Promise.withResolvers() (ES2024)?
Correct Answer
A method returning { promise, resolve, reject } so the resolver functions can be used outside the Promise constructor
Explanation
const { promise, resolve, reject } = Promise.withResolvers() replaces the deferred pattern. Useful when resolve/reject must be called from different places.
36
What is the iterator helpers proposal (Stage 3) in JavaScript?
Correct Answer
Built-in map, filter, take, drop, and other lazy methods directly on iterators via Iterator.prototype
Explanation
function* gen() { yield* [1,2,3,4,5]; } gen().filter(x => x > 2).take(2).toArray() — lazy iterator operations without materializing to array first.
37
What is the Object.groupBy() method (ES2024)?
Correct Answer
A static method that groups iterable elements into an object based on a key-returning callback
Explanation
Object.groupBy([{type:"a"},{type:"b"},{type:"a"}], x => x.type) returns { a: [...], b: [...] }. Map.groupBy() does the same for Map results.
38
What is the RegExp v flag (ES2024)?
Correct Answer
A Unicode sets mode enabling character class set operations, string properties, and improved Unicode support
Explanation
/[A-Z&&[^AEIOU]]/v matches uppercase consonants using set intersection. The v flag extends u flag with character class set algebra.
39
What is the TC39 decorators proposal (Stage 3)?
Correct Answer
A standard way to add metadata and modify class elements using @decorator syntax, standardized after years of TypeScript usage
Explanation
@logged class Foo { @bound onClick() {} } — TC39 stage 3 decorators work differently from TypeScript decorators (legacy). They receive descriptor objects, not constructor/prototype.
40
What is the difference between Array.prototype.flatMap() and map().flat()?
Correct Answer
flatMap is equivalent to map().flat(1) but more efficient as it performs both operations in a single pass
Explanation
[1,2,3].flatMap(x => [x, x*2]) = [1,2,2,4,3,6] in one pass. .map().flat(1) does two iterations over the array.
1
What is the V8 engine's hidden class (shape) optimization?
Correct Answer
An internal structure V8 creates to represent object layouts, allowing fast property access when objects share the same shape
Explanation
V8 assigns hidden classes (shapes) to objects with the same property sequence. Adding properties in a consistent order lets V8 optimize property access via static offsets.
2
What is the event loop's relationship with the call stack and Web APIs?
Correct Answer
Web APIs (timers, fetch) run outside the JS thread; callbacks are queued in the task queue and the event loop moves them to the call stack when it is empty
Explanation
JavaScript is single-threaded. Browser Web APIs handle async work. Callbacks are placed in macrotask/microtask queues and processed by the event loop when the stack empties.
3
What is realm in JavaScript contexts?
Correct Answer
An isolated global environment (its own global object, intrinsics, and code) — iframes and workers run in separate realms
Explanation
Each realm has its own Array, Object, etc. An array from another realm fails instanceof Array in the main realm — use Array.isArray() for cross-realm checks.
4
What is the difference between AbortController and CancellationToken?
Correct Answer
AbortController is the browser/Node.js native cancellation primitive; CancellationToken is a C# concept but inspired AbortSignal patterns
Explanation
AbortController.signal is passed to fetch/streams/EventListeners. Calling controller.abort() cancels the operation. It is now available in Node.js as well.
5
What is tail call optimization (TCO) in JavaScript?
Correct Answer
An optimization where the call stack frame is reused for a tail-position function call, preventing stack overflow in deep recursion
Explanation
TCO was mandated by ES6 strict mode but only Safari implements it. A tail call is a function call as the last action with no further work after it returns.
6
What is the difference between structuredClone and the history state algorithm?
Correct Answer
structuredClone uses the same Structured Clone Algorithm used by postMessage, history.pushState, and IndexedDB to deep-serialize transferable objects
Explanation
The Structured Clone Algorithm supports more types than JSON (Date, Map, Set, ArrayBuffer, circular refs) and is shared by structuredClone, postMessage, and storage APIs.
7
What is the purpose of TransferableObjects with postMessage?
Correct Answer
Objects (like ArrayBuffer) whose ownership is transferred to the recipient, zeroing the sender's reference to avoid copying
Explanation
Transferring an ArrayBuffer moves ownership to the worker (zero-copy). The original becomes detached. SharedArrayBuffer allows actual shared memory.
8
What is a JavaScript engine's inline cache (IC)?
Correct Answer
A JIT optimization that caches type feedback at call sites to avoid repeated type checks on repeated invocations
Explanation
Monomorphic ICs (one shape) are fastest. Polymorphic (few shapes) are acceptable. Megamorphic ICs (many shapes) degrade to slow hash lookups — keep object shapes consistent.
9
What does the stage proposal process mean for JavaScript features?
Correct Answer
TC39's four-stage process (0-4) that proposals go through before becoming part of the ECMAScript standard
Explanation
Stage 0 is strawman; Stage 4 is finished (in the spec). Stage 3 is candidate (browsers start implementing). Features at Stage 3 are stable enough to use with transpilation.
10
What is the difference between ESM and CJS module systems?
Correct Answer
ESM (import/export) is statically analyzed, supports live bindings, and is async; CJS (require) is synchronous, dynamic, and copies values
Explanation
ESM is the standard. CJS is Node.js legacy. ESM enables tree shaking. ESM bindings are live (updating with the exported value). CJS require() is synchronous blocking.
11
What is a BigInt in JavaScript and when would you use it?
Correct Answer
An arbitrary-precision integer type (suffix n: 9007199254740993n) used when values exceed Number.MAX_SAFE_INTEGER
Explanation
Number can't represent integers above 2^53-1 accurately. BigInt (42n) supports arbitrary size. BigInt and Number cannot be mixed in arithmetic without explicit conversion.
12
What is the difference between JSON.parse() reviver and JSON.stringify() replacer?
Correct Answer
Replacer is a function/array filtering/transforming values during stringify; reviver transforms parsed values during parse
Explanation
JSON.stringify(obj, (k,v) => v instanceof Date ? v.toISO() : v) serializes dates. JSON.parse(str, (k,v) => /\d{4}-/.test(v) ? new Date(v) : v) restores them.
13
What is the V8 engine's deoptimization?
Correct Answer
Converting optimized code back to bytecode when type assumptions are violated
Explanation
V8 optimizes based on observed types. If an int-optimized function receives a string, it deoptimizes (bails out) back to bytecode interpretation. Avoid mixing types in performance-critical functions.
14
What is the JavaScript abstract machine and how does it relate to spec compliance?
Correct Answer
The ECMAScript specification defines an abstract machine with algorithms for operations; engines must implement observable behavior consistently, not the exact steps
Explanation
The ECMAScript spec defines abstract operations. Engines may optimize freely as long as observable behavior (side effects, return values) matches. The spec itself runs on an abstract machine.
15
What is the Temporal Dead Zone for let/const class fields?
Correct Answer
When a derived class constructor calls methods before super(), accessing class fields defined in the base triggers TDZ since fields are initialized by super()
Explanation
Calling a base method in a derived constructor before super() that accesses the base's fields risks TDZ errors because field initialization happens as part of super().
16
What is the AsyncLocalStorage API in Node.js?
Correct Answer
A Node.js API providing per-request context propagation similar to thread-local storage, using AsyncLocalStorage and AsyncResource
Explanation
asyncLocalStorage.run({ requestId }, () => handler()) propagates requestId through all async continuations within that run, enabling request-scoped logging without prop drilling.
17
What is the JavaScript engine's code cache?
Correct Answer
Compiled bytecode cached to disk by engines (V8 Code Caching) so subsequent page loads skip parsing and compilation for unchanged scripts
Explanation
V8 serializes compiled bytecode after a script's second visit to a page. Browsers store it alongside HTTP cache. Speeds up cold starts for large frameworks.
18
What is the Node.js Worker Threads module?
Correct Answer
True OS threads in Node.js sharing ArrayBuffer via SharedArrayBuffer, enabling CPU-intensive work without blocking the event loop
Explanation
worker_threads allow JavaScript code to run in parallel threads sharing SharedArrayBuffer. Unlike child_process, Workers share memory, making them efficient for CPU-bound work.
19
What is the difference between WebAssembly.Memory and regular JavaScript ArrayBuffer?
Correct Answer
WebAssembly.Memory is a resizable, page-aligned memory object (64KB pages) specifically designed for WASM modules, shareable as SharedArrayBuffer
Explanation
WebAssembly.Memory grows in 64KB pages and exposes its underlying ArrayBuffer. JavaScript can read/write it directly. Can be declared as shared for multi-threaded WASM modules.
20
What is the JavaScript type coercion for addition with objects?
Correct Answer
Objects are converted to primitives via valueOf() or toString(); {} + [] returns 0 because {} is parsed as an empty block in statement position
Explanation
({}) + [] = "[object Object]" when {} is an expression. At statement level, {} is a block and + [] = 0. This is one of JavaScript's most confusing coercion behaviors.