JavaScript Advanced MCQs

1 min read

Advanced JavaScript mastery requires a deep understanding of the language’s inner runtime mechanics, memory management, and asynchronous concurrency models. Senior-level evaluations frequently probe into topics such as the Event Loop’s microtask and macrotask prioritization, lexical closures, advanced prototypal delegation, Proxy and Reflect APIs, and generators. Recognizing how the V8 engine handles execution contexts, property descriptors, and low-level type coercion enables developers to write highly optimized, bug-free applications. These advanced multiple-choice questions are designed to test deep conceptual fluency and prepare candidates for rigorous technical interviews.

1. Which of the following describes a closure in JavaScript?

a) A function that is executed immediately after its definition
b) A function combined with references to its lexical environment
c) An object that stores private variables globally
d) A mechanism to handle asynchronous operations
Correct Answer: b) A function combined with references to its lexical environment
Explanation:
A closure is a function bundled together with references to its lexical environment, allowing it to remember and access variables from an outer function even after that outer function has finished executing.

2. What is the primary purpose of the 'prototype' property in JavaScript functions?

a) To define private instance variables
b) To establish inheritance by sharing methods across instances
c) To optimize garbage collection for function execution contexts
d) To store the return value of a constructor function
Correct Answer: b) To establish inheritance by sharing methods across instances
Explanation:
Every constructor function has a prototype property that is used to build prototype chains, enabling all instances created by that constructor to share common methods and properties efficiently.

3. How does the JavaScript engine handle asynchronous operations via the Event Loop?

a) By executing all callback functions concurrently on separate CPU threads
b) By pushing tasks directly from the call stack to the microtask queue
c) By moving completed asynchronous callbacks from queues to the call stack when empty
d) By blocking the main thread until network requests return a response
Correct Answer: c) By moving completed asynchronous callbacks from queues to the call stack when empty
Explanation:
The event loop continuously checks if the call stack is empty. If it is, it takes the first task from the microtask or macrotask queue and pushes it to the call stack for execution.

4. Which of the following statements about Promises is correct?

a) A Promise can transition from pending to fulfilled or rejected multiple times
b) A Promise represents a value that may be available now, in the future, or never
c) Promises execute asynchronously on a separate web worker thread by default
d) The .catch() method prevents any preceding .then() handlers from running
Correct Answer: b) A Promise represents a value that may be available now, in the future, or never
Explanation:
A Promise is a proxy for a value not necessarily known when the promise is created. It transitions once from pending to either fulfilled or rejected and remains settled.

5. What is the output of typeof null in JavaScript?

a) null
b) undefined
c) object
d) number
Correct Answer: c) object
Explanation:
This is a well-known historical bug in JavaScript. In the first implementation of JavaScript, values were represented as type tags and values, and the tag for objects was 0. null was represented as the NULL pointer (0x00), causing typeof to report it as an object.

6. What is the difference between Object.freeze() and Object.seal()?

a) Object.freeze() makes properties read-only, while Object.seal() allows modifying existing property values
b) Object.seal() prevents adding new properties, while Object.freeze() prevents both adding and modifying properties
c) Object.freeze() deletes all nested objects, whereas Object.seal() preserves them
d) There is no functional difference; they are aliases for strict mode objects
Correct Answer: b) Object.seal() prevents adding new properties, while Object.freeze() prevents both adding and modifying properties
Explanation:
Object.seal() prevents adding or deleting properties but allows changing the values of existing properties. Object.freeze() goes further by making existing properties non-writable as well.

7. Which of the following methods creates a shallow copy of an object?

a) JSON.parse(JSON.stringify(obj))
b) Object.assign({}, obj)
c) structuredClone(obj)
d) Object.create(obj)
Correct Answer: b) Object.assign({}, obj)
Explanation:
Object.assign copies enumerable own properties from one or more source objects to a target object, creating a shallow copy. structuredClone creates a deep copy, and JSON methods handle deep copies for JSON-safe data.

8. What does the 'this' keyword refer to inside an arrow function?

a) The global window object in strict mode
b) The object that invokes the arrow function
c) The lexical enclosing context where the arrow function is defined
d) A dynamically bound execution context determined at call time
Correct Answer: c) The lexical enclosing context where the arrow function is defined
Explanation:
Arrow functions do not have their own 'this' binding. Instead, they inherit 'this' lexically from their enclosing execution context.

9. What is a Generator function in JavaScript?

a) A function that automatically generates unit test cases
b) A function that can be exited and later re-entered, maintaining its context
c) A factory pattern used exclusively for creating class instances
d) An asynchronous function that returns a Promise automatically
Correct Answer: b) A function that can be exited and later re-entered, maintaining its context
Explanation:
Generator functions, defined with function*, can be paused using the yield keyword and resumed later, maintaining their internal state across invocations.

10. Which statement correctly describes Microtasks versus Macrotasks?

a) Macrotasks have higher priority than microtasks in the event loop
b) Promises and queueMicrotask callbacks execute as microtasks before the next macrotask
c) setTimeout callbacks are executed as microtasks
d) Microtasks run only after all macrotasks in all queues are completely empty
Correct Answer: b) Promises and queueMicrotask callbacks execute as microtasks before the next macrotask
Explanation:
The event loop empties the entire microtask queue after the call stack clears and before moving on to the next macrotask (such as setTimeout or DOM rendering).

11. What is the purpose of a JavaScript Proxy object?

a) To route network requests through a designated server endpoint
b) To intercept and customize operations performed on target objects
c) To encrypt sensitive data stored in local storage
d) To simulate multiple inheritance in ES6 classes
Correct Answer: b) To intercept and customize operations performed on target objects
Explanation:
A Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations like property lookup, assignment, enumeration, and function invocation.

12. What is event bubbling in the DOM?

a) Events propagate from the target element up to the root ancestor
b) Events propagate from the root ancestor down to the target element
c) Events trigger randomly across sibling elements in a container
d) Events are captured only during the target phase
Correct Answer: a) Events propagate from the target element up to the root ancestor
Explanation:
Event bubbling is the phase of event propagation where an event triggered on a nested child element bubbles up through its parents to the document root.

13. How can you prevent an event from bubbling up the DOM tree?

a) event.preventDefault()
b) event.stopPropagation()
c) event.stopImmediatePropagation() only for capture phase
d) return false in native event listeners
Correct Answer: b) event.stopPropagation()
Explanation:
Calling event.stopPropagation() prevents the current event from bubbling further up the DOM tree, though other listeners on the same element will still run.

14. What is memoization in JavaScript?

a) A technique to automatically manage memory leaks in closures
b) An optimization technique that caches the results of expensive function calls
c) A memory allocation strategy for large TypedArrays
d) A garbage collection algorithm used by V8 engines
Correct Answer: b) An optimization technique that caches the results of expensive function calls
Explanation:
Memoization stores the return values of function calls based on input parameters, returning the cached result if the same inputs occur again.

15. What does the 'async/await' syntax syntactic sugar represent?

a) Web Workers running in separate threads
b) Generators combined with Promises
c) Synchronous blocking execution for HTTP requests
d) Direct callback functions managed by the compiler
Correct Answer: b) Generators combined with Promises
Explanation:
Async/await syntax is built on top of promises and generator concepts, allowing asynchronous code to be written in a cleaner, synchronous-looking style.

16. What is the result of evaluating: [1, 2, 3] + [4, 5, 6] in JavaScript?

a) [1, 2, 3, 4, 5, 6]
b) "1,2,34,5,6"
c) NaN
d) 15
Correct Answer: b) "1,2,34,5,6"
Explanation:
When the + operator is used with arrays, JavaScript converts both arrays to strings using their toString() method ('1,2,3' and '4,5,6') and concatenates them into a single string.

17. Which of the following is a primitive data type introduced in ES2020?

a) Symbol
b) BigInt
c) WeakRef
d) Map
Correct Answer: b) BigInt
Explanation:
BigInt was introduced in ES2020 to represent whole numbers larger than the 2^53 - 1 safe integer limit for standard Numbers.

18. What is the purpose of WeakMap in JavaScript?

a) To store key-value pairs with strong references preventing garbage collection
b) To store object keys weakly, allowing them to be garbage collected if no other references exist
c) To provide synchronized thread-safe maps for multi-threaded workers
d) To automatically serialize maps into JSON format
Correct Answer: b) To store object keys weakly, allowing them to be garbage collected if no other references exist
Explanation:
WeakMap keys must be objects, and the references are weak, meaning they do not prevent garbage collection if the key object has no other active references.

19. What is lexical scoping?

a) Variable visibility determined by where variables are declared in the source code
b) Dynamic variable binding based on the function call stack
c) The rules governing how keywords are tokenized by the JS compiler
d) Variable scoping restricted strictly to switch-case blocks
Correct Answer: a) Variable visibility determined by where variables are declared in the source code
Explanation:
Lexical scoping (or static scoping) means that a variable's accessibility is determined by its physical location within the nested code blocks at compile time.

20. What does the strict mode ('use strict') directive prevent?

a) Using arrow functions in object methods
b) Implicit global variable creation by assigning to undeclared identifiers
c) Using async/await inside loops
d) Declaring variables with let and const
Correct Answer: b) Implicit global variable creation by assigning to undeclared identifiers
Explanation:
Strict mode throws an error when assigning values to undeclared variables, preventing accidental creation of global variables, along with other silent errors.

21. What is the difference between call(), apply(), and bind()?

a) call and apply invoke the function immediately with arguments passed differently, while bind returns a new bound function
b) bind invokes immediately, while call and apply return deferred functions
c) apply works only with arrow functions, while call works with regular functions
d) There is no difference; they are interchangeable method aliases
Correct Answer: a) call and apply invoke the function immediately with arguments passed differently, while bind returns a new bound function
Explanation:
call() takes arguments individually, apply() takes arguments as an array, and bind() returns a new function with a permanently bound 'this' context.

22. What is hoisting in JavaScript?

a) Moving variable and function declarations to the top of their scope during compilation
b) Elevating the priority of microtasks over macrotasks in the event loop
c) Automatically lifting DOM elements to the top layer of the rendering tree
d) Promoting local variables to global scope when memory is low
Correct Answer: a) Moving variable and function declarations to the top of their scope during compilation
Explanation:
Hoisting is JavaScript's default behavior of moving declarations to the top of their current scope during the compilation phase before code execution.

23. Which of the following statements about const declarations is correct?

a) Variables declared with const are completely immutable
b) Variables declared with const must be initialized at the time of declaration and cannot be reassigned
c) Variables declared with const are hoisted and initialized with undefined
d) Variables declared with const have function scope
Correct Answer: b) Variables declared with const must be initialized at the time of declaration and cannot be reassigned
Explanation:
const prevents reassignment of the variable identifier, but if the value is an object or array, its internal properties or elements can still be mutated.

24. What is the output of: console.log(1 + '2' + 3);

a) 6
b) "123"
c) "33"
d) 123
Correct Answer: b) "123"
Explanation:
Evaluation goes left to right. 1 + '2' results in string concatenation '12'. Then '12' + 3 results in further string concatenation yielding '123'.

25. What is a JavaScript Symbol used for?

a) Creating encrypted string tokens
b) Generating unique, immutable identifiers suitable for object property keys
c) Representing mathematical constants like Pi and Infinity
d) Defining template literal tags
Correct Answer: b) Generating unique, immutable identifiers suitable for object property keys
Explanation:
Symbols are primitive values guaranteed to be unique, making them ideal for creating hidden or collision-free object property keys.

26. What is the Temporal Dead Zone (TDZ)?

a) The time period between a network timeout and promise rejection
b) The state where variables declared with let and const exist in scope but are not yet initialized
c) The delay before setTimeout callbacks execute in the event loop
d) The execution phase after garbage collection runs
Correct Answer: b) The state where variables declared with let and const exist in scope but are not yet initialized
Explanation:
The TDZ is the zone from the start of the block scope until the variable declaration is evaluated, during which accessing the variable throws a ReferenceError.

27. How do you check if a property exists directly on an object (not on its prototype chain)?

a) 'prop' in obj
b) obj.hasOwnProperty('prop') or Object.hasOwn(obj, 'prop')
c) obj.prop !== undefined
d) Object.keys(obj).includes('prop') only
Correct Answer: b) obj.hasOwnProperty('prop') or Object.hasOwn(obj, 'prop')
Explanation:
hasOwnProperty and the modern Object.hasOwn() check whether the property is a direct (own) property of the object, ignoring the prototype chain.

28. What is the purpose of the Array.prototype.reduce() method?

a) To filter out elements that do not match a condition
b) To flatten multi-dimensional arrays into a single array
c) To execute a reducer function on each element, resulting in a single accumulated output value
d) To shrink array size by removing duplicate elements
Correct Answer: c) To execute a reducer function on each element, resulting in a single accumulated output value
Explanation:
reduce() applies a function against an accumulator and each element in the array to reduce it to a single value.

29. What does Promise.all() do when one of the passed promises rejects?

a) It ignores the rejected promise and returns results of the successful ones
b) It immediately rejects with the reason of the first rejected promise
c) It waits for all promises to finish before throwing an aggregate error
d) It retries the failed promise up to three times
Correct Answer: b) It immediately rejects with the reason of the first rejected promise
Explanation:
Promise.all() fails fast: if any promise in the iterable rejects, the returned promise immediately rejects with that rejection reason.

30. What is the difference between Promise.all() and Promise.allSettled()?

a) allSettled waits for all promises to settle (fulfill or reject) and returns an array of status objects
b) allSettled rejects immediately if any promise fails, unlike all
c) allSettled only works with async/await functions
d) There is no difference; they are synonyms
Correct Answer: a) allSettled waits for all promises to settle (fulfill or reject) and returns an array of status objects
Explanation:
Promise.allSettled() never short-circuits; it waits until all input promises have completed, reporting their outcome status ('fulfilled' or 'rejected').

31. What is function currying?

a) A technique of evaluating a function with multiple arguments into a sequence of functions each with a single argument
b) Asynchronous error handling using try/catch blocks
c) Binding object methods to DOM event listeners
d) Converting callback-based functions into Promises
Correct Answer: a) A technique of evaluating a function with multiple arguments into a sequence of functions each with a single argument
Explanation:
Currying transforms a function of form f(a, b, c) into a chain of unary functions: f(a)(b)(c).

32. What is debouncing in JavaScript?

a) Ensuring a function is called at most once in a specified time period regardless of how often it's triggered
b) Delaying execution of a function until a certain amount of time has elapsed since the last time it was invoked
c) Removing debugger statements automatically during minification
d) Cleaning up memory references after event unbinding
Correct Answer: b) Delaying execution of a function until a certain amount of time has elapsed since the last time it was invoked
Explanation:
Debouncing postpones function execution until after a specified wait period has passed since the last trigger (useful for search input or window resizing).

33. What is throttling in JavaScript?

a) Limiting the rate at which a function can fire, ensuring it runs at most once every specified interval
b) Pausing execution until network bandwidth improves
c) Canceling pending promises when component unmounts
d) Restricting recursion depth to prevent stack overflow
Correct Answer: a) Limiting the rate at which a function can fire, ensuring it runs at most once every specified interval
Explanation:
Throttling ensures a function is executed at regular intervals (e.g., once every 100ms) no matter how many times it's triggered during that window.

34. What is tail call optimization (TCO)?

a) Optimizing recursive functions so that a recursive call in tail position does not consume extra stack space
b) Garbage collecting unused tail arrays in memory
c) Reordering event listeners so bubbled events execute faster
d) Minimizing bundle size by removing trailing semicolons
Correct Answer: a) Optimizing recursive functions so that a recursive call in tail position does not consume extra stack space
Explanation:
TCO allows engines to reuse the current stack frame for tail-recursive calls, preventing stack overflow errors for deep recursion.

35. What is the purpose of the Reflect object in JavaScript?

a) To provide interceptor methods that mirror Proxy traps for executing default behavior
b) To inspect component metadata in React applications
c) To reflect DOM changes back to server-side templates
d) To debug asynchronous stack traces
Correct Answer: a) To provide interceptor methods that mirror Proxy traps for executing default behavior
Explanation:
The Reflect API provides static methods for interceptable JavaScript operations, making it easy to invoke default behavior from inside Proxy handlers.

36. What is the output of: typeof NaN?

a) NaN
b) undefined
c) number
d) object
Correct Answer: c) number
Explanation:
In JavaScript, NaN (Not-a-Number) is classified technically as a numeric data type value representing an invalid number.

37. How does prototypal inheritance differ from classical inheritance?

a) Prototypal inheritance relies on objects inheriting directly from other objects rather than classes
b) Classical inheritance uses prototypes under the hood without classes
c) Prototypal inheritance does not support method overriding
d) There is no difference; classes in ES6 are completely classical
Correct Answer: a) Prototypal inheritance relies on objects inheriting directly from other objects rather than classes
Explanation:
JavaScript uses prototypal inheritance where objects link directly to other objects via the prototype chain ([[Prototype]]), rather than instantiating class blueprints.

38. What is the purpose of Object.preventExtensions()?

a) It prevents new properties from being added to an object
b) It freezes all property values against modification
c) It deletes all inherited prototype properties
d) It stops methods from being called on the object
Correct Answer: a) It prevents new properties from being added to an object
Explanation:
Object.preventExtensions() makes an object non-extensible, meaning no new properties can be added, though existing properties can still be modified or deleted.

39. What is the return value of an async function that does not explicitly return a value?

a) undefined
b) A Promise resolved with undefined
c) null
d) An empty object {}
Correct Answer: b) A Promise resolved with undefined
Explanation:
All async functions automatically wrap their return values (or implicit undefined return) in a resolved Promise.

40. What is the output of: Boolean('false')?

a) false
b) true
c) TypeError
d) undefined
Correct Answer: b) true
Explanation:
'false' is a non-empty string, which is a truthy value in JavaScript. Only empty strings ('') evaluate to false when cast to Boolean.

41. What is the difference between interface/types in TypeScript and runtime checks in JavaScript?

a) TypeScript types are erased at compile time, whereas JavaScript requires runtime type validation
b) JavaScript enforces strict typing at runtime
c) TypeScript types are preserved in compiled runtime bundles
d) JavaScript has built-in static type annotations
Correct Answer: a) TypeScript types are erased at compile time, whereas JavaScript requires runtime type validation
Explanation:
JavaScript is dynamically typed and performs no compile-time checks, requiring explicit runtime validation libraries or typeof/instanceof checks.

42. What is the purpose of queueMicrotask()?

a) To schedule a microtask to be run asynchronously before the browser renders or handles the next macrotask
b) To execute functions immediately on the main call stack
c) To delay execution by a specified millisecond timeout
d) To spawn a background web worker thread
Correct Answer: a) To schedule a microtask to be run asynchronously before the browser renders or handles the next macrotask
Explanation:
queueMicrotask safely queues custom callbacks into the microtask queue, ensuring they run after the current script and before any macrotasks.

43. What does Object.is(val1, val2) do compared to strict equality (===)?

a) Object.is treats NaN as equal to NaN and distinguishes +0 from -0
b) Object.is performs type coercion, unlike ===
c) Object.is compares object references by deep structural equality
d) There is no difference; Object.is is an alias for ===
Correct Answer: a) Object.is treats NaN as equal to NaN and distinguishes +0 from -0
Explanation:
While === considers NaN !== NaN and +0 === -0, Object.is correctly evaluates Object.is(NaN, NaN) as true and Object.is(+0, -0) as false.

44. What is the purpose of the CSS/JS concept of Event Delegation?

a) Handling events at a common parent element instead of attaching listeners to individual child elements
b) Delegating event handling to a remote server worker
c) Stopping events from bubbling past the document root
d) Delegating rendering tasks to GPU threads
Correct Answer: a) Handling events at a common parent element instead of attaching listeners to individual child elements
Explanation:
Event delegation leverages event bubbling to handle events on a single parent element for multiple current or future child elements efficiently.

45. What is a JavaScript module (ESM)?

a) A file that executes in strict mode by default, with its own top-level scope and explicit import/export statements
b) A global namespace object containing utility functions
c) An asynchronous wrapper around CommonJS require()
d) A class definition with private methods
Correct Answer: a) A file that executes in strict mode by default, with its own top-level scope and explicit import/export statements
Explanation:
ES Modules (ESM) have their own lexical scope, automatically run in strict mode, and support static import and export syntax.

46. What is the output of: [] == ![]?

a) true
b) false
c) TypeError
d) undefined
Correct Answer: a) true
Explanation:
![] evaluates to false (as array is truthy). Then [] == false compares an array to a boolean. Boolean is converted to number (0), and [] is converted to primitive '' then 0, so 0 == 0 evaluates to true.

47. What is the difference between Map and Set collections?

a) Map stores key-value pairs, while Set stores unique values without keys
b) Set stores key-value pairs, while Map stores unique values only
c) Map keys can only be strings, while Set accepts any data type
d) Set maintains insertion order, while Map does not
Correct Answer: a) Map stores key-value pairs, while Set stores unique values without keys
Explanation:
A Map holds key-value pairs where keys can be of any type. A Set is a collection of unique values where each value occurs only once.

48. What is structural typing in TypeScript / object shapes?

a) Compatibility is determined by having matching properties and types, regardless of explicit nominal type declarations
b) Compatibility is determined strictly by class names
c) Objects must be instantiated using constructor functions
d) Data structures are validated against XML schemas at runtime
Correct Answer: a) Compatibility is determined by having matching properties and types, regardless of explicit nominal type declarations
Explanation:
JavaScript and TypeScript use structural typing (duck typing), meaning if an object has the required structure/shape, it is considered compatible.

49. What is the purpose of the 'finally' block in try...catch statements?

a) It executes regardless of whether an exception was thrown or caught, useful for cleanup tasks
b) It catches asynchronous promise rejections that try blocks miss
c) It overrides error messages thrown in the catch block
d) It terminates the event loop if an unhandled error occurs
Correct Answer: a) It executes regardless of whether an exception was thrown or caught, useful for cleanup tasks
Explanation:
The finally block always runs after try and catch execution finishes, making it ideal for closing connections, releasing locks, or cleaning up state.

50. What is the output of: 0.1 + 0.2 === 0.3?

a) true
b) false
c) TypeError
d) NaN
Correct Answer: b) false
Explanation:
Due to IEEE 754 double-precision floating-point arithmetic representation, 0.1 + 0.2 evaluates to 0.30000000000000004, not exactly 0.3.

51. What is a JavaScript Sanitizer / Sanitization technique used for?

a) Preventing Cross-Site Scripting (XSS) by stripping malicious HTML/JS payloads from untrusted input
b) Minifying JavaScript code for production deployment
c) Removing whitespace and comments to speed up parsing
d) Validating JSON schemas against API endpoints
Correct Answer: a) Preventing Cross-Site Scripting (XSS) by stripping malicious HTML/JS payloads from untrusted input
Explanation:
Sanitization cleans untrusted strings or DOM nodes to prevent XSS attacks by removing executable script tags and dangerous attributes.

52. What does the optional chaining operator (?.) do?

a) It short-circuits and returns undefined if a reference is null or undefined, preventing runtime errors
b) It checks if a property exists and throws an error if it is missing
c) It forces type coercion on optional function parameters
d) It provides default fallback values like the nullish coalescing operator
Correct Answer: a) It short-circuits and returns undefined if a reference is null or undefined, preventing runtime errors
Explanation:
Optional chaining (?.) allows safe access to deeply nested object properties without needing to explicitly check if each intermediate reference is nullish.

53. What does the nullish coalescing operator (??) do?

a) It returns the right-hand side operand when the left-hand side is null or undefined
b) It returns the right-hand side operand when the left-hand side is falsy (including 0 and '')
c) It performs logical OR operation with type coercion
d) It assigns default values to uninitialized let declarations
Correct Answer: a) It returns the right-hand side operand when the left-hand side is null or undefined
Explanation:
Unlike || which falls back on any falsy value (like 0 or false), ?? strictly checks for null or undefined before returning the fallback value.

54. What is an Immediately Invoked Function Expression (IIFE)?

a) A function defined as an expression that executes immediately upon creation
b) An asynchronous function executed via the event loop queue
c) A method called on an object constructor immediately
d) An arrow function that returns a Promise
Correct Answer: a) A function defined as an expression that executes immediately upon creation
Explanation:
An IIFE runs as soon as it is defined, commonly used in pre-ES6 code to create a private scope and prevent polluting the global namespace.

55. What is the purpose of the Intl object in JavaScript?

a) To provide language-sensitive string comparison, number formatting, and date/time formatting
b) To manage international network routing protocols
c) To handle internationalization of JSON payloads
d) To translate error messages into multiple languages automatically
Correct Answer: a) To provide language-sensitive string comparison, number formatting, and date/time formatting
Explanation:
The Intl namespace is the ECMAScript Internationalization API, offering robust formatting and collation tools tailored to user locales.

56. What is the difference between Object.keys(), Object.values(), and Object.entries()?

a) Keys returns property names, values returns property values, and entries returns [key, value] arrays
b) Keys returns prototype properties, values returns own properties, entries returns both
c) They are formatting aliases for JSON.stringify
d) Keys returns arrays, while values and entries return Maps
Correct Answer: a) Keys returns property names, values returns property values, and entries returns [key, value] arrays
Explanation:
Object.keys returns an array of a given object's own property names, Object.values returns property values, and Object.entries returns key-value pairs.

57. What is the purpose of the structuredClone() function?

a) To create a deep clone of a value using the structured clone algorithm
b) To clone DOM element structures without event listeners
c) To serialize objects into structured XML format
d) To duplicate database records asynchronously
Correct Answer: a) To create a deep clone of a value using the structured clone algorithm
Explanation:
structuredClone() creates deep copies of complex JavaScript objects, supporting circular references, dates, regexps, maps, sets, and TypedArrays.

58. What is the role of the V8 JavaScript engine?

a) To compile and execute JavaScript code directly to native machine code using JIT compilation
b) To interpret JavaScript into bytecode interpreted line-by-line without compilation
c) To manage CSS layout rendering engines
d) To compile TypeScript into HTML5 documents
Correct Answer: a) To compile and execute JavaScript code directly to native machine code using JIT compilation
Explanation:
V8 (used in Chrome and Node.js) compiles JavaScript directly to machine code using Just-In-Time (JIT) compilation for high execution performance.

59. What is a memory leak in JavaScript?

a) When memory that is no longer needed by an application is not released back to the system due to retained references
b) When RAM hardware fails during script execution
c) When the call stack exceeds its maximum recursion limit
d) When local storage exceeds its 5MB quota limit
Correct Answer: a) When memory that is no longer needed by an application is not released back to the system due to retained references
Explanation:
A memory leak occurs when objects are no longer needed but remain reachable via active roots or closures, preventing the garbage collector from reclaiming their memory.

60. Which of the following is a common cause of memory leaks in single-page applications?

a) Uncleaned event listeners, forgotten timers, and detached DOM node references
b) Using const instead of var for variable declarations
c) Writing pure functions without side effects
d) Using async/await instead of callbacks
Correct Answer: a) Uncleaned event listeners, forgotten timers, and detached DOM node references
Explanation:
Failing to remove event listeners, clear setInterval timers, or releasing references to removed DOM elements keeps them in memory, causing leaks.

61. What is the purpose of the 'debugger' statement in JavaScript?

a) It invokes any available debugging functionality, such as setting a breakpoint in developer tools
b) It prints stack trace error logs to the console
c) It pauses the event loop permanently until network debugging connects
d) It compiles source maps for production debugging
Correct Answer: a) It invokes any available debugging functionality, such as setting a breakpoint in developer tools
Explanation:
The debugger statement halts code execution if developer tools are open, acting as a programmatic breakpoint.

62. What does 'Array.prototype.flat(depth)' do?

a) It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth
b) It removes duplicate elements from nested arrays
c) It converts multi-dimensional arrays into flat JSON strings
d) It flattens object properties into a single level
Correct Answer: a) It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth
Explanation:
flat() flattens nested arrays. By default it flattens one level deep, but you can pass a depth number or Infinity to flatten completely.

63. What is the purpose of 'Array.prototype.flatMap() '?

a) It first maps each element using a mapping function, then flattens the result into a new array of depth 1
b) It flattens an array before running map filters
c) It creates a flat map collection (similar to a Map data structure)
d) It flattens asynchronous promises in parallel
Correct Answer: a) It first maps each element using a mapping function, then flattens the result into a new array of depth 1
Explanation:
flatMap is identical to mapping and then flattening 1 level deep, making it more efficient than calling map() and flat() separately.

64. What is the difference between encodeURI() and encodeURIComponent()?

a) encodeURI does not encode special characters used in URI structure like ?, /, and #, whereas encodeURIComponent encodes them
b) encodeURIComponent is used for full URLs, while encodeURI is for query parameters
c) There is no difference; they are aliases
d) encodeURI encodes unicode characters, while encodeURIComponent does not
Correct Answer: a) encodeURI does not encode special characters used in URI structure like ?, /, and #, whereas encodeURIComponent encodes them
Explanation:
encodeURI is meant for complete URLs, preserving syntactic characters. encodeURIComponent is meant for individual query parameter values and encodes all special characters.

65. What is a JavaScript TypedArray used for?

a) To read and write raw binary data in memory buffers with high performance
b) To enforce strict TypeScript types at runtime in the browser
c) To store typed key-value maps efficiently
d) To validate form input types before submission
Correct Answer: a) To read and write raw binary data in memory buffers with high performance
Explanation:
TypedArrays (like Float32Array, Uint8Array) provide a mechanism for reading and writing raw binary data in underlying ArrayBuffers.

66. What is the role of an ArrayBuffer in JavaScript?

a) It represents a generic, fixed-length raw binary data buffer
b) It is a temporary cache buffer for array sorting operations
c) It buffers asynchronous array push events
d) It provides garbage collection buffering for large datasets
Correct Answer: a) It represents a generic, fixed-length raw binary data buffer
Explanation:
An ArrayBuffer is a data type used to represent a generic fixed-length raw binary data buffer, accessed via TypedArray or DataView views.

67. What is property shadowing in JavaScript prototypes?

a) When an object defines a property with the same name as a property on its prototype chain, hiding the prototype's property
b) When a closure hides global variables from outer scopes
c) When private class fields block public method access
d) When strict mode shadows undeclared variables
Correct Answer: a) When an object defines a property with the same name as a property on its prototype chain, hiding the prototype's property
Explanation:
Property shadowing occurs when an instance property takes precedence over a prototype property with the exact same name during lookups.

68. What is the difference between Object.freeze() and const?

a) const prevents variable reassignment, while Object.freeze() makes object properties immutable
b) Object.freeze() prevents variable reassignment, while const makes object properties immutable
c) They perform the exact same operation on objects
d) const works only on arrays, Object.freeze works on objects
Correct Answer: a) const prevents variable reassignment, while Object.freeze() makes object properties immutable
Explanation:
const restricts variable binding reassignment. Object.freeze() mutates the object itself, making its properties non-writable, non-configurable, and non-extensible.

69. What is the output of: typeof typeof 1?

a) "string"
b) "number"
c) "undefined"
d) "object"
Correct Answer: a) "string"
Explanation:
typeof 1 evaluates to the string "number". Then typeof "number" evaluates to the string "string".

70. What is the purpose of the 'with' statement in JavaScript, and why is it deprecated?

a) It extends the scope chain temporarily, but it causes severe performance optimizations issues and ambiguity and is forbidden in strict mode
b) It allows safe multi-property object destructuring
c) It replaces try/catch blocks for error handling
d) It imports modules dynamically
Correct Answer: a) It extends the scope chain temporarily, but it causes severe performance optimizations issues and ambiguity and is forbidden in strict mode
Explanation:
The 'with' statement adds an object to the head of the scope chain during evaluation, making variable resolution ambiguous and preventing JIT optimizations.

71. What is a JavaScript Tagged Template?

a) A way to parse template literals with a function, receiving the string parts and interpolated expressions separately
b) A method to generate HTML DOM tags from strings
c) A template engine library built into ES6
d) A regex pattern matcher for XML tags
Correct Answer: a) A way to parse template literals with a function, receiving the string parts and interpolated expressions separately
Explanation:
Tagged templates allow you to customize template literal parsing by passing strings and evaluated expressions to a custom tag function.

72. What is the output of: 3 > 2 > 1?

a) false
b) true
c) TypeError
d) NaN
Correct Answer: a) false
Explanation:
Evaluation goes left to right: (3 > 2) evaluates to true. Then true > 1 evaluates true to numeric 1, and 1 > 1 evaluates to false.

73. What is the purpose of the AbortController interface in JavaScript?

a) To abort asynchronous operations like fetch requests or event listeners via an AbortSignal
b) To cancel running web worker threads
c) To stop infinite loops in JavaScript execution
d) To rollback transaction states in IndexedDB
Correct Answer: a) To abort asynchronous operations like fetch requests or event listeners via an AbortSignal
Explanation:
AbortController allows you to abort ongoing fetch requests, DOM events, or async tasks using an associated AbortSignal instance.

74. What is dynamic import (`import()`) used for in JavaScript?

a) To load modules asynchronously on-demand (code splitting) returning a Promise
b) To import modules conditionally at the top of a file without a Promise
c) To reload cached modules from disk automatically
d) To import external scripts via HTTP without CORS restrictions
Correct Answer: a) To load modules asynchronously on-demand (code splitting) returning a Promise
Explanation:
Dynamic import() allows loading ES modules conditionally or on-demand at runtime, returning a promise that resolves to the module module object.

75. What is the difference between a shallow clone and a deep clone?

a) A shallow clone copies top-level properties (nested objects remain reference-linked), while a deep clone recursively copies all nested objects
b) A shallow clone copies prototype methods, while a deep clone copies only own properties
c) A shallow clone runs synchronously, while a deep clone requires async execution
d) There is no difference in memory allocation
Correct Answer: a) A shallow clone copies top-level properties (nested objects remain reference-linked), while a deep clone recursively copies all nested objects
Explanation:
Shallow copies duplicate references of nested objects, meaning mutations affect both. Deep copies duplicate the entire nested structure recursively.

76. What is the purpose of WeakRef in JavaScript?

a) To hold a weak reference to an object without preventing it from being garbage collected
b) To create weak closures that do not capture outer variables
c) To manage weak DOM node references in React virtual DOMs
d) To optimize memory allocation for primitive numbers
Correct Answer: a) To hold a weak reference to an object without preventing it from being garbage collected
Explanation:
WeakRef allows you to hold a weak reference to an object, letting you check if it still exists without preventing garbage collection.

77. What is a FinalizationRegistry in JavaScript?

a) An API that lets you request a callback when an object is garbage collected
b) A registry for tracking Promise settlement states
c) A database registry for browser offline storage
d) A tool to monitor event listener cleanup
Correct Answer: a) An API that lets you request a callback when an object is garbage collected
Explanation:
FinalizationRegistry lets you register a callback function that is invoked after an unregistered target object has been garbage collected.

78. What is the purpose of the 'name' property on JavaScript functions?

a) It returns the string name of the function as declared or inferred by the engine
b) It stores unique identifier symbols for constructor functions
c) It is used by closures to bind lexical environments
d) It determines how functions are serialized into JSON
Correct Answer: a) It returns the string name of the function as declared or inferred by the engine
Explanation:
The function.name property returns the name of the function or infers it from variable/property assignments during declaration.

79. What does a constructor return by default if no return statement is specified?

a) The newly created instance ('this')
b) undefined
c) null
d) An empty object {}
Correct Answer: a) The newly created instance ('this')
Explanation:
If a constructor function or class constructor does not explicitly return an object, it implicitly returns the newly created instance ('this').

80. What happens if a constructor explicitly returns a primitive value (e.g., return 10)?

a) The primitive return value is ignored, and the new instance ('this') is returned
b) The constructor returns the primitive value instead of the instance
c) A TypeError is thrown by the JavaScript engine
d) The primitive is converted to an object wrapper
Correct Answer: a) The primitive return value is ignored, and the new instance ('this') is returned
Explanation:
Constructors in JavaScript ignore primitive return values and continue returning the newly constructed object instance.

81. What happens if a constructor explicitly returns an object (e.g., return {a: 1})?

a) That returned object becomes the result of the new expression, overriding 'this'
b) The returned object is merged with the new instance
c) A TypeError is thrown
d) The return statement is ignored
Correct Answer: a) That returned object becomes the result of the new expression, overriding 'this'
Explanation:
If a constructor explicitly returns an object reference, that object is returned as the result of the 'new' operator expression, discarding 'this'.

82. What is the output of: typeof class {};

a) "function"
b) "object"
c) "class"
d) "undefined"
Correct Answer: a) "function"
Explanation:
Classes in JavaScript are syntactical sugar over prototype-based constructor functions, so typeof class evaluates to "function".

83. Can JavaScript classes be hoisted like traditional function declarations?

a) No, class declarations are hoisted but remain uninitialized in the Temporal Dead Zone until evaluation
b) Yes, they are fully hoisted and callable before their line of declaration
c) No, classes are never hoisted under any circumstances
d) Yes, but only in non-strict mode
Correct Answer: a) No, class declarations are hoisted but remain uninitialized in the Temporal Dead Zone until evaluation
Explanation:
Like let and const, class declarations are hoisted to the top of their scope but remain in the TDZ, throwing a ReferenceError if accessed before declaration.

84. What is the purpose of private class fields (# syntax)?

a) To enforce true private encapsulation within class bodies, inaccessible from outside the class
b) To protect fields from being overwritten by prototype inheritance
c) To encrypt class properties in memory buffers
d) To optimize class compilation in V8 engines
Correct Answer: a) To enforce true private encapsulation within class bodies, inaccessible from outside the class
Explanation:
Private fields prefixed with # provide native language-level encapsulation, ensuring they cannot be accessed or modified outside the class scope.

85. What is method borrowing in JavaScript?

a) Using call(), apply(), or bind() to borrow methods from one object/prototype and use them on another
b) Inheriting classes via multiple inheritance patterns
c) Importing methods across different ES modules
d) Overriding prototype methods dynamically
Correct Answer: a) Using call(), apply(), or bind() to borrow methods from one object/prototype and use them on another
Explanation:
Method borrowing lets an object use methods belonging to another prototype or object (such as borrowing Array methods for array-like arguments objects) using call/apply.

86. What is the purpose of Object.create(proto)?

a) To create a new object with its internal [[Prototype]] explicitly linked to the specified proto object
b) To clone an object deeply including its prototype methods
c) To register a new object in the global scope
d) To instantiate a class without calling its constructor
Correct Answer: a) To create a new object with its internal [[Prototype]] explicitly linked to the specified proto object
Explanation:
Object.create() creates a new object using an existing object as the prototype of the newly created object.

87. What is the difference between instanceof and typeof?

a) typeof checks primitive data types, while instanceof checks if an object's prototype chain contains a constructor's prototype
b) instanceof checks primitives, while typeof checks constructor prototypes
c) They perform the exact same type checks on all values
d) instanceof works only with primitive strings and numbers
Correct Answer: a) typeof checks primitive data types, while instanceof checks if an object's prototype chain contains a constructor's prototype
Explanation:
typeof returns a string description of primitive types. instanceof checks whether a constructor's prototype property appears anywhere within an object's prototype chain.

88. What is polyfilling in JavaScript development?

a) Providing code that implements modern JavaScript features on older environments that lack native support
b) Minifying source code to reduce network transfer size
c) Translating TypeScript interfaces into runtime validation code
d) Bundling multiple modules into a single execution file
Correct Answer: a) Providing code that implements modern JavaScript features on older environments that lack native support
Explanation:
A polyfill is a piece of code (or plugin) that provides modern native APIs (like Array.prototype.flat or Promise) on older browsers that do not support them natively.

89. What is transpiling?

a) Source-to-source compiling, such as converting ES6+ or TypeScript code into backward-compatible ES5 JavaScript
b) Converting JavaScript bytecode into native machine CPU instructions
c) Compiling JavaScript into WebAssembly binaries
d) Minifying CSS and JavaScript assets for production
Correct Answer: a) Source-to-source compiling, such as converting ES6+ or TypeScript code into backward-compatible ES5 JavaScript
Explanation:
Transpilers (like Babel or TypeScript compiler) take source code in one language/version and transform it into equivalent source code in another version or language.

90. What is WebAssembly (Wasm) and how does it relate to JavaScript?

a) A low-level binary format that runs alongside JavaScript in browsers at near-native speed, interoperable with JS
b) A replacement framework that deprecates JavaScript entirely
c) A server-side runtime environment for executing Node.js modules
d) An alternative DOM manipulation library
Correct Answer: a) A low-level binary format that runs alongside JavaScript in browsers at near-native speed, interoperable with JS
Explanation:
WebAssembly is a binary instruction format designed for high-performance applications in web browsers, working seamlessly alongside JavaScript.

91. What is the purpose of a JavaScript Web Worker?

a) To run scripts in background threads separate from the main execution thread, preventing UI blocking
b) To manage network socket connections asynchronously
c) To handle DOM rendering tasks in parallel
d) To cache web pages for offline Progressive Web Apps
Correct Answer: a) To run scripts in background threads separate from the main execution thread, preventing UI blocking
Explanation:
Web Workers allow running CPU-intensive scripts in background threads, keeping the main UI thread responsive without freezing.

92. How do Web Workers communicate with the main thread?

a) Via asynchronous message passing using postMessage() and message event listeners
b) By sharing direct access to global variables and DOM nodes
c) Through synchronized mutex locks on shared memory buffers
d) Using direct function calls across thread boundaries
Correct Answer: a) Via asynchronous message passing using postMessage() and message event listeners
Explanation:
Workers do not share shared memory state (unless using SharedArrayBuffer), so they communicate by passing messages back and forth using postMessage and onmessage.

93. What is the Service Worker lifecycle responsible for?

a) Intercepting network requests, caching assets, and enabling offline functionality for web applications
b) Managing background database synchronization for IndexedDB
c) Handling UI component mounting and unmounting
d) Executing server-side Node.js routing logic
Correct Answer: a) Intercepting network requests, caching assets, and enabling offline functionality for web applications
Explanation:
Service Workers act as proxy servers between web apps and the network, enabling offline experiences, push notifications, and asset caching.

94. What is the purpose of the Shadow DOM?

a) To encapsulate component markup, styles, and behavior, preventing global CSS leakage and DOM collision
b) To render hidden background DOM nodes for performance optimization
c) To store virtual DOM trees in React applications
d) To obscure sensitive user data from screen scrapers
Correct Answer: a) To encapsulate component markup, styles, and behavior, preventing global CSS leakage and DOM collision
Explanation:
Shadow DOM allows hidden decoupled DOM trees to be attached to elements, providing native scoping for styles and markup (key for Web Components).

95. What is the difference between Shadow DOM and Virtual DOM?

a) Shadow DOM is a browser technology for DOM/CSS encapsulation, while Virtual DOM is a programming concept used by libraries like React for efficient reconciliation
b) Virtual DOM is built into the browser, while Shadow DOM is a React library feature
c) They perform the exact same rendering optimization tasks
d) Shadow DOM is deprecated in favor of Virtual DOM
Correct Answer: a) Shadow DOM is a browser technology for DOM/CSS encapsulation, while Virtual DOM is a programming concept used by libraries like React for efficient reconciliation
Explanation:
Shadow DOM is a W3C browser standard for encapsulation. Virtual DOM is a lightweight in-memory representation of real DOM elements used by UI libraries to batch and optimize diffing/updates.

96. What is the JavaScript Garbage Collector's primary algorithm for detecting unused memory?

a) Mark-and-sweep algorithm
b) Reference counting only without cycle detection
c) First-in-first-out memory purging
d) Stack allocation tracking
Correct Answer: a) Mark-and-sweep algorithm
Explanation:
Modern JavaScript engines primarily use a 'mark-and-sweep' algorithm, which periodically traverses object graphs starting from roots to identify and collect unreachable objects.

97. What is a circular reference in JavaScript, and how does modern garbage collection handle it?

a) When two or more objects reference each other; modern mark-and-sweep collectors handle them successfully by checking reachability from roots
b) When functions call themselves infinitely, causing stack overflow
c) When modules import each other, causing runtime crashes
d) When prototype chains loop back to Object.prototype
Correct Answer: a) When two or more objects reference each other; modern mark-and-sweep collectors handle them successfully by checking reachability from roots
Explanation:
While pure reference-counting collectors failed on circular references, modern mark-and-sweep garbage collectors detect them easily because they check if objects are reachable from root pointers.

98. What is the purpose of the 'Object.freeze()' recursive deep freeze implementation?

a) Standard freeze is shallow; a deep freeze recursively applies Object.freeze to all nested object properties
b) It freezes the prototype chain as well as instance properties
c) It prevents garbage collection of frozen objects
d) It serializes objects into read-only binary buffers
Correct Answer: a) Standard freeze is shallow; a deep freeze recursively applies Object.freeze to all nested object properties
Explanation:
Object.freeze() only freezes top-level properties. To make an entire nested object structure immutable, you must recursively traverse and freeze all nested objects.

99. What is the output of: console.log(typeof ([]));

a) "object"
b) "array"
c) "undefined"
d) "list"
Correct Answer: a) "object"
Explanation:
Arrays are specialized objects in JavaScript, so typeof [] returns "object". To check for arrays specifically, use Array.isArray().
← Previous: Java Variables & Data Types MCQs
Next →: JavaScript Arrays & Array Methods MCQs
Java Interfaces and Abstract Classes MCQs

Java Interfaces and Abstract Classes MCQs

Java interfaces and abstract classes are core constructs used to implement abstraction and enforce design contracts in object-oriented architecture. An…

By MCQs Generator
No Image

C++ Exception / Error Handling - MCQs

1. Which of the following describes a closure in JavaScript? a) A function that is executed immediately after its definition…

By MCQs Generator
JavaScript Closures MCQs

JavaScript Closures MCQs for Senior Developer Interviews

A closure in JavaScript is formed when an inner function retains access to the variables of its outer enclosing lexical…

By MCQs Generator