JavaScript Interview Questions MCQs

1 min read

JavaScript interview questions evaluate a developer’s deep understanding of core language mechanics, execution models, and advanced runtime behavior. Top tech companies frequently test concepts like lexical scoping, closures, prototypal inheritance, and the single-threaded event loop. Mastering these technical pillars is critical for passing front-end and full-stack software engineering interviews. These practice questions cover frequent technical hurdles encountered during developer screenings.

1. What is a closure in JavaScript?

a) A function bundled together with references to its lexical environment, allowing access to outer scope variables after the outer function has closed.
b) An error handling block used to close database connections safely.
c) A compiler directive that optimizes code execution speed.
d) A built-in method for terminating active worker threads.
Correct Answer: a) A function bundled together with references to its lexical environment, allowing access to outer scope variables after the outer function has closed.
Explanation:
Closures allow inner functions to retain access to variables in their outer enclosing scope even after the outer function execution context has returned.

2. What is the output of `typeof null` in JavaScript?

a) "object"
b) "null"
c) "undefined"
d) "number"
Correct Answer: a) "object"
Explanation:
Due to a historical bug in the initial implementation of JavaScript where object type tags were 0 and null was represented as the null pointer, `typeof null` incorrectly returns "object".

3. What is the primary difference between `==` and `===` operators?

a) `===` checks both value and type without type coercion, whereas `==` performs type conversion before comparing values.
b) `==` is strictly faster than `===` in V8 runtime execution.
c) `===` only compares object references, not primitive values.
d) `==` evaluates strictly for prototype chain inheritance.
Correct Answer: a) `===` checks both value and type without type coercion, whereas `==` performs type conversion before comparing values.
Explanation:
The strict equality operator (`===`) evaluates both value and data type, preventing unexpected bugs caused by implicit type coercion.

4. What is event bubbling in the DOM?

a) The propagation of events from the innermost target element upwards through its parent ancestors in the DOM tree.
b) The capturing phase where events travel from the document root down to the target node.
c) An automatic memory garbage collection cycle for unattached event listeners.
d) A technique for rendering DOM elements using background Web Workers.
Correct Answer: a) The propagation of events from the innermost target element upwards through its parent ancestors in the DOM tree.
Explanation:
Event bubbling causes an event triggered on a child element to ripple upward through all its parent container elements up to the document root.

5. How can you stop an event from propagating further through the DOM tree?

a) Calling `event.stopPropagation()`
b) Calling `event.preventDefault()`
c) Setting `event.cancelBubble = false`
d) Returning `false` from the global window object
Correct Answer: a) Calling `event.stopPropagation()`
Explanation:
stopPropagation prevents the current event from bubbling or capturing further through parent or child nodes.

6. What is event delegation?

a) A technique where a single event listener is attached to a parent element to manage events on its current and future child elements efficiently.
b) Delegating event handling to a background Web Worker thread.
c) Passing event objects across iframe boundaries.
d) Removing event listeners automatically upon garbage collection.
Correct Answer: a) A technique where a single event listener is attached to a parent element to manage events on its current and future child elements efficiently.
Explanation:
Event delegation leverages bubbling to handle events centrally on parent containers, reducing memory overhead and supporting dynamically added elements.

7. What does the `this` keyword refer to inside a standard function call in non-strict mode?

a) The global object (`window` in browsers)
b) `undefined`
c) The enclosing parent object literal
d) The global `document` object
Correct Answer: a) The global object (`window` in browsers)
Explanation:
In non-strict mode, calling a standard standalone function binds `this` to the global object, whereas strict mode defaults `this` to `undefined`.

8. How does `this` behave inside an arrow function compared to a standard function?

a) Arrow functions do not bind their own `this`; they lexically inherit `this` from their surrounding enclosing execution context.
b) Arrow functions always bind `this` to the global window object permanently.
c) Arrow functions bind `this` to the event target automatically.
d) Arrow functions throw a TypeError when accessing `this`.
Correct Answer: a) Arrow functions do not bind their own `this`; they lexically inherit `this` from their surrounding enclosing execution context.
Explanation:
Arrow functions lack their own `this` binding, making them ideal for callbacks where preserving outer context `this` is necessary.

9. What is the purpose of the `call()` method on functions?

a) To invoke a function with a specified `this` value and arguments passed individually as comma-separated parameters.
b) To delay function execution asynchronously.
c) To bind arguments permanently to a function template.
d) To convert a function into a Promise object.
Correct Answer: a) To invoke a function with a specified `this` value and arguments passed individually as comma-separated parameters.
Explanation:
Function.prototype.call immediately executes the function with a custom `this` context and individual arguments.

10. What is the difference between `call()` and `apply()`?

a) `call` accepts arguments individually separated by commas, whereas `apply` accepts arguments as a single array.
b) `apply` executes synchronously, while `call` executes asynchronously.
c) `call` creates a permanent bound copy, while `apply` invokes once.
d) There is no difference between them.
Correct Answer: a) `call` accepts arguments individually separated by commas, whereas `apply` accepts arguments as a single array.
Explanation:
Both invoke functions immediately with a custom `this`, but apply takes an array of arguments while call takes comma-separated arguments.

11. What does the `bind()` method do?

a) It returns a brand new function with a permanently bound `this` context and optional preset arguments, without executing it immediately.
b) It executes the function immediately and returns its return value.
c) It binds two objects together via prototypal inheritance.
d) It connects DOM elements to event handlers.
Correct Answer: a) It returns a brand new function with a permanently bound `this` context and optional preset arguments, without executing it immediately.
Explanation:
Unlike call and apply which execute immediately, bind returns a bound function ready for later invocation.

12. What is prototypal inheritance in JavaScript?

a) A mechanism where objects can inherit properties and methods directly from other template objects through their internal prototype chain (`[[Prototype]]`).
b) A classical class-based inheritance model identical to Java or C++.
c) An automatic copying mechanism that clones object properties into memory.
d) A garbage collection routine for prototype definitions.
Correct Answer: a) A mechanism where objects can inherit properties and methods directly from other template objects through their internal prototype chain (`[[Prototype]]`).
Explanation:
JavaScript uses prototypes rather than classes for inheritance, allowing objects to delegate property lookups up the prototype chain.

13. What is the prototype chain?

a) The linked sequence of internal prototype references (`[[Prototype]]`) connecting an object up to `Object.prototype` and ultimately `null` for property resolution.
b) A chain of asynchronous callback functions.
c) The inheritance hierarchy of DOM element nodes.
d) A collection of bound `this` contexts.
Correct Answer: a) The linked sequence of internal prototype references (`[[Prototype]]`) connecting an object up to `Object.prototype` and ultimately `null` for property resolution.
Explanation:
When accessing a property, the engine searches the object itself and traverses up its prototype chain until found or reaching `null`.

14. What is the Event Loop in JavaScript?

a) A runtime mechanism that continuously monitors the call stack and task queues, executing callbacks when the stack becomes empty.
b) A CPU thread optimization for parallel multi-core rendering.
c) An infinite `while` loop used to process user mouse movements.
d) A memory allocation cycle for garbage collection.
Correct Answer: a) A runtime mechanism that continuously monitors the call stack and task queues, executing callbacks when the stack becomes empty.
Explanation:
The event loop orchestrates JavaScript's asynchronous concurrency model, coordinating the call stack, microtask queue, and macrotask queue.

15. What is the difference between microtasks and macrotasks in the event loop?

a) Microtasks (e.g., Promises, `queueMicrotask`) have higher priority and execute immediately after the current stack empties before rendering, whereas macrotasks (e.g., `setTimeout`) execute in subsequent event loop ticks.
b) Macrotasks execute faster than microtasks.
c) Microtasks run on separate worker threads.
d) There is no priority difference.
Correct Answer: a) Microtasks (e.g., Promises, `queueMicrotask`) have higher priority and execute immediately after the current stack empties before rendering, whereas macrotasks (e.g., `setTimeout`) execute in subsequent event loop ticks.
Explanation:
The event loop drains the entire microtask queue before moving on to the next macrotask.

16. Which of the following is classified as a microtask in JavaScript?

a) Promise `.then()` / `.catch()` / `.finally()` callbacks
b) `setTimeout()` callback
c) `setInterval()` callback
d) `requestAnimationFrame()` callback
Correct Answer: a) Promise `.then()` / `.catch()` / `.finally()` callbacks
Explanation:
Promise resolution handlers queue as microtasks, executing prior to macrotasks like timers.

17. Which of the following is classified as a macrotask?

a) `setTimeout()`
b) Promise `.then()`
c) `queueMicrotask()`
d) MutationObserver callback
Correct Answer: a) `setTimeout()`
Explanation:
Timers like setTimeout and setInterval schedule callbacks onto the macrotask (task) queue.

18. What is a Promise in JavaScript?

a) An object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
b) A synchronous locking mechanism for multi-threaded file access.
c) A callback wrapper that forces code to execute synchronously.
d) An event listener for DOM mutations.
Correct Answer: a) An object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Explanation:
Promises provide a cleaner, chainable abstraction for handling asynchronous code compared to nested callbacks.

19. What are the three possible states of a JavaScript Promise?

a) Pending, Fulfilled, and Rejected
b) Active, Paused, and Terminated
c) Waiting, Success, and Error
d) Uninitialized, Resolved, and Closed
Correct Answer: a) Pending, Fulfilled, and Rejected
Explanation:
A promise starts in a pending state and settles into either fulfilled (resolved with value) or rejected (failed with reason).

20. What is the behavior of `async/await` syntax?

a) It is syntactic sugar over Promises, allowing asynchronous code to be written in a synchronous-looking, readable manner using `await` to pause execution until a promise settles.
b) It converts asynchronous code into true multi-threaded native machine threads.
c) It disables the event loop entirely during execution.
d) It automatically converts synchronous loops into Web Workers.
Correct Answer: a) It is syntactic sugar over Promises, allowing asynchronous code to be written in a synchronous-looking, readable manner using `await` to pause execution until a promise settles.
Explanation:
Async/await makes asynchronous logic cleaner by avoiding explicit `.then()` chaining.

21. What is currying in functional programming?

a) The technique of translating a function that takes multiple arguments into a sequence of nested functions that each take a single argument.
b) Spicing up code readability with arrow functions.
c) Converting synchronous functions into asynchronous promises.
d) Caching function return results based on inputs.
Correct Answer: a) The technique of translating a function that takes multiple arguments into a sequence of nested functions that each take a single argument.
Explanation:
Currying transforms `f(a, b, c)` into `f(a)(b)(c)`, enabling partial application.

22. What is memoization?

a) An optimization technique that caches the return values of expensive function calls based on their input parameters to avoid redundant computations.
b) An automatic memory cleanup garbage collection routine.
c) A tool for recording browser memory performance profiles.
d) Storing state variables inside closure scopes.
Correct Answer: a) An optimization technique that caches the return values of expensive function calls based on their input parameters to avoid redundant computations.
Explanation:
Memoization speeds up pure functions by returning cached results when given identical inputs.

23. What is debouncing in JavaScript?

a) A technique that limits the rate at which a function fires by delaying execution until a specified amount of time has elapsed since the last time it was invoked.
b) Ensuring a function executes at most once every specified fixed time interval.
c) Removing event listeners to prevent memory leaks.
d) Catching runtime exceptions in asynchronous code.
Correct Answer: a) A technique that limits the rate at which a function fires by delaying execution until a specified amount of time has elapsed since the last time it was invoked
Explanation:
Debouncing resets a timer on every trigger, making it ideal for search input autocomplete where you only want to fire after typing stops.

24. What is throttling in JavaScript?

a) A technique that ensures a function is called at most once per specified time period, regardless of how many times the event fires.
b) Delaying function execution until user inactivity occurs.
c) Limiting network bandwidth for fetch requests.
d) Restricting recursive function call stack depth.
Correct Answer: a) A technique that ensures a function is called at most once per specified time period, regardless of how many times the event fires.
Explanation:
Throttling guarantees regular execution intervals (e.g., once every 100ms), perfect for window scroll or resize handlers.

25. What is a shallow copy of an object?

a) A copy where top-level primitive properties are cloned, but nested objects and arrays are copied by reference rather than duplicated.
b) A complete deep clone of all nested structures in memory.
c) An object reference pointing to the exact same memory address.
d) An immutable proxy object.
Correct Answer: a) A copy where top-level primitive properties are cloned, but nested objects and arrays are copied by reference rather than duplicated.
Explanation:
Methods like `Object.assign()` or spread syntax (`{...obj}`) create shallow copies, meaning nested objects are still shared.

26. What is a deep copy of an object?

a) A complete duplicate of an object and all its nested sub-objects and arrays, ensuring no references are shared with the original.
b) A copy of prototype methods only.
c) A frozen object instance.
d) An object stored in browser local storage.
Correct Answer: a) A complete duplicate of an object and all its nested sub-objects and arrays, ensuring no references are shared with the original.
Explanation:
Deep copies (e.g., using `structuredClone()`) recursively duplicate all nested structures.

27. What does `structuredClone()` do in modern JavaScript?

a) It creates a deep copy of any serializable JavaScript value natively without external libraries.
b) It parses JSON strings into typed arrays.
c) It formats database schemas into objects.
d) It serializes DOM nodes into HTML strings.
Correct Answer: a) It creates a deep copy of any serializable JavaScript value natively without external libraries.
Explanation:
structuredClone is the built-in standard for deep cloning objects supporting cyclic references and various data types.

28. What is type coercion in JavaScript?

a) The automatic or implicit conversion of values from one data type to another (e.g., string to number).
b) Explicitly declaring variable types using TypeScript annotations.
c) Throwing a TypeError when passing invalid arguments.
d) Compiling JavaScript into WebAssembly bytes.
Correct Answer: a) The automatic or implicit conversion of values from one data type to another (e.g., string to number).
Explanation:
JavaScript performs implicit coercion in operations like `'5' + 2` resulting in `'52'`.

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

a) The execution phase where `let` and `const` variables exist in scope before their declaration line, throwing a ReferenceError if accessed.
b) The time period when asynchronous setTimeout timers wait.
c) The garbage collection pause window in the V8 engine.
d) The period before DOMContentLoaded fires.
Correct Answer: a) The execution phase where `let` and `const` variables exist in scope before their declaration line, throwing a ReferenceError if accessed.
Explanation:
TDZ prevents accessing block-scoped variables prior to their actual initialization line.

30. What is a Higher-Order Function?

a) A function that takes one or more functions as arguments, returns a function, or both.
b) A function declared at the top of the global scope.
c) An async function that returns a Promise.
d) A constructor class method.
Correct Answer: a) A function that takes one or more functions as arguments, returns a function, or both.
Explanation:
Array methods like `map`, `filter`, and `reduce` are classic examples of higher-order functions.

31. What does the `Array.prototype.map()` method do?

a) It creates a brand new array populated with the results of calling a provided function on every element in the calling array.
b) It filters elements based on a boolean condition.
c) It mutates the original array in place with transformed values.
d) It reduces array elements down to a single accumulated value.
Correct Answer: a) It creates a brand new array populated with the results of calling a provided function on every element in the calling array.
Explanation:
map transforms each element and returns a new array without mutating the original.

32. What does the `Array.prototype.filter()` method do?

a) It creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the provided function.
b) It modifies the original array by removing failing elements.
c) It returns the first single element matching a condition.
d) It flattens nested arrays.
Correct Answer: a) It creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the provided function.
Explanation:
filter evaluates a predicate function for each item and includes items returning true in a new array.

33. What does the `Array.prototype.reduce()` method do?

a) It executes a user-supplied reducer callback function on each element of the array, resulting in a single output value.
b) It reduces the total memory size of an array.
c) It removes duplicate values from an array.
d) It sorts array elements in descending order.
Correct Answer: a) It executes a user-supplied reducer callback function on each element of the array, resulting in a single output value.
Explanation:
reduce accumulates array values into a single result (such as a sum, object, or grouped structure).

34. What is the difference between `Array.prototype.find()` and `Array.prototype.filter()`?

a) `find` returns the first single element that satisfies the testing function, whereas `filter` returns a new array containing all matching elements.
b) `find` mutates the array, while `filter` does not.
c) `find` returns a boolean, while `filter` returns an object.
d) There is no difference.
Correct Answer: a) `find` returns the first single element that satisfies the testing function, whereas `filter` returns a new array containing all matching elements.
Explanation:
find stops searching and returns the element as soon as a match is found, whereas filter collects all matches.

35. What is the purpose of `Object.freeze()`?

a) It freezes an object so that existing properties cannot be added, removed, or modified (making it immutable at the top level).
b) It serializes an object into compressed binary data.
c) It prevents garbage collection of the object reference.
d) It converts object properties into read-only symbols.
Correct Answer: a) It freezes an object so that existing properties cannot be added, removed, or modified (making it immutable at the top level).
Explanation:
Object.freeze makes an object shallowly immutable; nested objects can still be mutated unless frozen recursively.

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

a) `Object.freeze()` makes properties non-writable and non-configurable, whereas `Object.seal()` prevents adding or removing properties but allows modifying existing property values.
b) `Object.seal()` makes objects completely immutable.
c) `Object.freeze()` only works on arrays.
d) They perform identical operations.
Correct Answer: a) `Object.freeze()` makes properties non-writable and non-configurable, whereas `Object.seal()` prevents adding or removing properties but allows modifying existing property values.
Explanation:
Seal locks down structural property additions/deletions while permitting updates to existing property values.

37. What is a Proxy in JavaScript?

a) An object used to define custom behavior for fundamental operations on target objects, such as property lookup and assignment.
b) A network HTTP proxy client for fetch requests.
c) A wrapper for DOM event handlers.
d) A fallback constructor for older browsers.
Correct Answer: a) An object used to define custom behavior for fundamental operations on target objects, such as property lookup and assignment.
Explanation:
Proxies intercept and customize operations on target objects using handler traps like `get`, `set`, and `has`.

38. What is a Generator function?

a) A function that can be paused and resumed using the `yield` keyword, returning an iterator object that produces a sequence of values over time.
b) A utility that generates random UUID strings.
c) An automated unit test code generator.
d) A factory function for creating class instances.
Correct Answer: a) A function that can be paused and resumed using the `yield` keyword, returning an iterator object that produces a sequence of values over time.
Explanation:
Generator functions (declared with `function*`) yield multiple values lazily upon iterator `.next()` calls.

39. What is a Symbol in JavaScript?

a) A primitive data type whose instances are unique and immutable, commonly used as hidden or non-colliding object property keys.
b) A graphical icon rendered in DOM trees.
c) An alias for string variables.
d) A reserved keyword for class decorators.
Correct Answer: a) A primitive data type whose instances are unique and immutable, commonly used as hidden or non-colliding object property keys
Explanation:
Every Symbol() call creates a guaranteed unique value, preventing naming collisions on object properties.

40. What is the purpose of `WeakMap`?

a) A collection of key/value pairs where keys must be objects and are weakly referenced, allowing them to be garbage collected if unreferenced.
b) A Map that stores values with low memory encryption.
c) A synchronous dictionary for primitive strings.
d) A cache map that automatically clears every 60 seconds.
Correct Answer: a) A collection of key/value pairs where keys must be objects and are weakly referenced, allowing them to be garbage collected if unreferenced.
Explanation:
WeakMap prevents memory leaks by not preventing garbage collection of its key objects.

41. What is the difference between `Map` and `WeakMap`?

a) `Map` allows any data type as keys and strong references items, whereas `WeakMap` restricts keys strictly to objects with weak references allowing GC.
b) `WeakMap` supports iteration and `.size`, while `Map` does not.
c) `Map` keys are garbage collected automatically, while `WeakMap` keys are permanent.
d) There is no functional difference.
Correct Answer: a) `Map` allows any data type as keys and strong references items, whereas `WeakMap` restricts keys strictly to objects with weak references allowing GC.
Explanation:
WeakMaps are not iterable and have no size property because their keys can be garbage collected at any time.

42. What is garbage collection in JavaScript?

a) An automatic memory management mechanism performed by the engine to reclaim memory occupied by objects that are no longer reachable.
b) A routine that deletes browser cookies and cache storage.
c) Clearing DOM element event listeners when navigating pages.
d) Deleting temporary console log outputs.
Correct Answer: a) An automatic memory management mechanism performed by the engine to reclaim memory occupied by objects that are no longer reachable.
Explanation:
JavaScript engines use algorithms like Mark-and-Sweep to detect and clear unreachable memory.

43. What is a memory leak in JavaScript?

a) A situation where objects no longer needed are still inadvertently referenced in memory, preventing the garbage collector from reclaiming them.
b) A hardware failure in RAM sticks.
c) Excessive CPU consumption caused by infinite loops.
d) Data loss occurring during local storage quota overflow.
Correct Answer: a) A situation where objects no longer needed are still inadvertently referenced in memory, preventing the garbage collector from reclaiming them.
Explanation:
Common causes of memory leaks include dangling event listeners, forgotten timers, and global variable pollution.

44. What is strict mode (`'use strict'`) in JavaScript?

a) A directive that enforces stricter parsing and error handling rules, disabling unsafe features and throwing errors on silent failures.
b) A compilation mode that translates JavaScript into native C++ code.
c) A security setting that blocks cross-origin network fetch requests.
d) A formatting linter rule for indentation.
Correct Answer: a) A directive that enforces stricter parsing and error handling rules, disabling unsafe features and throwing errors on silent failures.
Explanation:
Strict mode catches common coding bloopers and turns silent errors into thrown exceptions.

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

a) A JavaScript function that runs as soon as it is defined, enclosed in parentheses to create a private lexical scope.
b) An asynchronous function executed immediately upon promise resolution.
c) A browser initialization event listener.
d) An error handling try/catch wrapper.
Correct Answer: a) A JavaScript function that runs as soon as it is defined, enclosed in parentheses to create a private lexical scope.
Explanation:
IIFE `(function() { ... })()` executes instantly, creating a private scope for variables before modules became standard.

46. What are ES6 Modules (`import` / `export`)?

a) The official standardized module system in JavaScript that loads files asynchronously with strict encapsulation and default strict mode.
b) A plugin library for loading JSON configuration files.
c) A bundler tool like Webpack.
d) HTML script tags with async attributes.
Correct Answer: a) The official standardized module system in JavaScript that loads files asynchronously with strict encapsulation and default strict mode.
Explanation:
ES6 modules provide native file-level scoping and static dependency analysis.

47. What is the difference between `null` and `undefined`?

a) `undefined` means a variable has been declared but not assigned a value, whereas `null` is an assignment value representing intentional absence of an object value.
b) `null` and `undefined` are strictly identical in data type and value.
c) `undefined` is an object, while `null` is a primitive number.
d) `null` is thrown by the compiler during syntax errors.
Correct Answer: a) `undefined` means a variable has been declared but not assigned a value, whereas `null` is an assignment value representing intentional absence of an object value.
Explanation:
Undefined is the default state of uninitialized variables, while null is explicitly assigned to denote 'no value'.

48. What is NaN in JavaScript?

a) "Not-A-Number", a special numeric value indicating that an operation intended to return a number failed or produced an invalid result.
b) A boolean flag indicating null array elements.
c) An uninitialized variable reference error.
d) A string formatting symbol.
Correct Answer: a) "Not-A-Number", a special numeric value indicating that an operation intended to return a number failed or produced an invalid result.
Explanation:
Despite standing for Not-A-Number, `typeof NaN` returns `"number"`, and `NaN !== NaN` is true.

49. How can you reliably check if a value is `NaN` in JavaScript?

a) Using `Number.isNaN(value)`
b) Using `value == NaN`
c) Using `typeof value === 'nan'`
d) Using `Object.isNotNull(value)`
Correct Answer: a) Using `Number.isNaN(value)`
Explanation:
Because `NaN !== NaN`, global `isNaN()` coerces non-numbers, making `Number.isNaN()` the safest reliable check.

50. What is the purpose of `Object.is()`?

a) To determine whether two values are the exact same value, handling edge cases like `NaN === NaN` (true) and `+0 !== -0` (false).
b) To check if an object inherits from a class.
c) To compare two objects for deep structural equality.
d) To verify if an object is frozen.
Correct Answer: a) To determine whether two values are the exact same value, handling edge cases like `NaN === NaN` (true) and `+0 !== -0` (false).
Explanation:
Object.is provides strict same-value equality comparisons superseding `===` limitations with NaN and zeroes.

51. What is a pure function?

a) A function that always returns the exact same output given the same input parameters and produces no observable side effects.
b) A function that executes inside a Web Worker thread.
c) A function declared without any parameters.
d) A function that mutates state immutably.
Correct Answer: a) A function that always returns the exact same output given the same input parameters and produces no observable side effects.
Explanation:
Pure functions have no side effects (like mutating global state or performing I/O), making them predictable and testable.

52. What is a side effect in programming?

a) Any modification of state outside the local function scope during execution, such as mutating global variables or modifying the DOM.
b) An unhandled promise rejection error.
c) A garbage collection memory pause.
d) A syntax error thrown during parsing.
Correct Answer: a) Any modification of state outside the local function scope during execution, such as mutating global variables or modifying the DOM.
Explanation:
Side effects make functions impure because their behavior depends on or alters external application state.

53. What is method chaining?

a) A programming pattern where multiple methods are invoked consecutively on the same object in a single statement by returning `this` or a new instance.
b) Chaining asynchronous callback functions together.
c) Inheriting prototype methods across five class levels.
d) Catching promise rejections in sequence.
Correct Answer: a) A programming pattern where multiple methods are invoked consecutively on the same object in a single statement by returning `this` or a new instance.
Explanation:
Method chaining (e.g., `arr.filter().map().reduce()`) allows fluent and concise code composition.

54. What is the Spread operator (`...`) used for?

a) To expand iterable elements or object properties into places where zero or more arguments or elements are expected.
b) To catch all remaining function arguments into an array.
c) To spread execution across multiple CPU threads.
d) To merge prototype chains.
Correct Answer: a) To expand iterable elements or object properties into places where zero or more arguments or elements are expected.
Explanation:
Spread syntax allows clean array/object copying and merging (`[...arr1, ...arr2]`).

55. What is the Rest parameter syntax (`...args`) used for?

a) To collect an indefinite number of comma-separated function arguments into a single true array.
b) To pause execution until network requests rest.
c) To capture unhandled promise rejections.
d) To store leftover properties during object destructuring.
Correct Answer: a) To collect an indefinite number of comma-separated function arguments into a single true array.
Explanation:
Rest parameters allow functions to accept variable numbers of arguments cleanly without relying on the legacy `arguments` object.

56. What is destructuring assignment in JavaScript?

a) A syntactic expression that unpacks values from arrays or properties from objects into distinct local variables.
b) Deleting object properties from memory.
c) Unlinking prototype chains during garbage collection.
d) Splitting strings into character arrays.
Correct Answer: a) A syntactic expression that unpacks values from arrays or properties from objects into distinct local variables.
Explanation:
Destructuring provides concise syntax for extracting data from objects and arrays (e.g., `const {name, age} = user`).

57. What is optional chaining (`?.`)?

a) A safe navigation operator that short-circuits property access and returns `undefined` if an intermediate reference is nullish instead of throwing a TypeError.
b) Chaining optional catch blocks in try/catch statements.
c) Optional promise resolution chaining.
d) Conditionally loading ES6 modules.
Correct Answer: a) A safe navigation operator that short-circuits property access and returns `undefined` if an intermediate reference is nullish instead of throwing a TypeError.
Explanation:
Optional chaining prevents 'Cannot read properties of undefined' crashes when traversing deep object trees.

58. What is the nullish coalescing operator (`??`)?

a) A logical operator that returns its right-hand side operand when its left-hand side operand is strictly `null` or `undefined`.
b) An operator that checks for falsy values like `0` or `""`.
c) A shorthand for ternary null checks.
d) An operator that throws errors on null values.
Correct Answer: a) A logical operator that returns its right-hand side operand when its left-hand side operand is strictly `null` or `undefined`.
Explanation:
Unlike `||` which treats `0` or `false` as falsy, `??` only falls back on `null` or `undefined`.

59. What are template literals in JavaScript?

a) String literals enclosed by backticks that allow embedded expressions, multi-line strings, and tagged template formatting.
b) HTML template tag selectors for DOM rendering.
c) JSON configuration schema templates.
d) Arrow function expression templates.
Correct Answer: a) String literals enclosed by backticks that allow embedded expressions, multi-line strings, and tagged template formatting.
Explanation:
Template literals support interpolation via `${expression}` and multi-line strings natively.

60. What is the DOM (Document Object Model)?

a) A programming interface that represents HTML and XML documents as a hierarchical tree of nodes, allowing scripts to manipulate structure and content.
b) A database storage system for browser cookies.
c) A CSS stylesheet compilation engine.
d) An asynchronous network protocol for web sockets.
Correct Answer: a) A programming interface that represents HTML and XML documents as a hierarchical tree of nodes, allowing scripts to manipulate structure and content.
Explanation:
The DOM bridges web pages and scripting languages like JavaScript, enabling dynamic page updates.

61. What is the difference between `childNodes` and `children` properties on DOM elements?

a) `childNodes` returns all child nodes including text and comment nodes, whereas `children` returns exclusively child element nodes.
b) `children` includes text nodes, while `childNodes` does not.
c) They return identical node collections.
d) `childNodes` is deprecated in modern browsers.
Correct Answer: a) `childNodes` returns all child nodes including text and comment nodes, whereas `children` returns exclusively child element nodes.
Explanation:
childNodes includes whitespace text nodes and comments, whereas children strictly returns HTML element nodes.

62. What is a CSS reflow (layout)?

a) The process where the browser calculates geometric dimensions and positions of DOM elements, which can cause performance jank if triggered excessively.
b) Repainting colors on screen without recalculating layout.
c) Compiling CSS stylesheets into binary WebAssembly.
d) Clearing browser cache memory during navigation.
Correct Answer: a) The process where the browser calculates geometric dimensions and positions of DOM elements, which can cause performance jank if triggered excessively.
Explanation:
Frequent layout reads/writes cause layout thrashing, severely degrading rendering performance.

63. What is a CSS repaint?

a) The process where the browser redraws elements on screen when visual styles change without altering layout geometry.
b) Recalculating element bounding box coordinates.
c) Rebuilding the entire DOM node tree.
d) Reloading external CSS stylesheet links.
Correct Answer: a) The process where the browser redraws elements on screen when visual styles change without altering layout geometry.
Explanation:
Repaints occur when style changes don't affect layout geometry, making them less expensive than reflows.

64. What is local storage (`localStorage`) in web browsers?

a) A web storage API that allows saving key-value pairs in a browser with no expiration time, persisting across sessions.
b) Temporary session storage cleared upon tab closure.
c) Encrypted server-side database storage.
d) IndexedDB document storage for binary files.
Correct Answer: a) A web storage API that allows saving key-value pairs in a browser with no expiration time, persisting across sessions.
Explanation:
localStorage stores string key-value pairs persistently across browser sessions until explicitly cleared.

65. What is the difference between `localStorage` and `sessionStorage`?

a) `localStorage` persists indefinitely until cleared, whereas `sessionStorage` is scoped to a single tab and deleted when closed.
b) `sessionStorage` persists across browser reboots, while `localStorage` does not.
c) `localStorage` stores binary objects, while `sessionStorage` stores strings.
d) There is no difference.
Correct Answer: a) `localStorage` persists indefinitely until cleared, whereas `sessionStorage` is scoped to a single tab and deleted when closed.
Explanation:
SessionStorage ties data lifetime strictly to the lifecycle of the browser tab session.

66. What is CORS (Cross-Origin Resource Sharing)?

a) An HTTP-header based security mechanism enforced by browsers allowing servers to specify permitted cross-origin resource access.
b) A protocol for sharing cookies across different domains securely.
c) A database replication protocol for distributed servers.
d) A JavaScript module loading standard.
Correct Answer: a) An HTTP-header based security mechanism enforced by browsers allowing servers to specify permitted cross-origin resource access.
Explanation:
CORS protects users by restricting cross-origin HTTP requests unless explicitly permitted by server headers.

67. What is a JSON Web Token (JWT)?

a) A compact, URL-safe means of representing claims securely between parties, consisting of a header, payload, and signature.
b) An encrypted database password hash.
c) A JSON configuration file for Webpack bundles.
d) An XML schema validation standard.
Correct Answer: a) A compact, URL-safe means of representing claims securely between parties, consisting of a header, payload, and signature.
Explanation:
JWTs are widely used for stateless authentication in web applications.

68. What is the purpose of `Object.create()`?

a) To create a new object, using an existing object as the prototype of the newly created object.
b) To serialize an object into JSON format.
c) To freeze an object's prototype chain.
d) To clone an object deeply.
Correct Answer: a) To create a new object, using an existing object as the prototype of the newly created object.
Explanation:
Object.create allows direct setup of prototypal inheritance links without constructor functions.

69. What are JavaScript TypedArrays?

a) Array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.
b) Arrays enforced with TypeScript type annotations at runtime.
c) Arrays that only accept primitive string types.
d) Immutable database query arrays.
Correct Answer: a) Array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.
Explanation:
TypedArrays handle raw binary data efficiently for WebGL, Web Audio, and binary file parsing.

70. What is a Web Worker?

a) A script running in a background thread separate from the main execution thread, allowing heavy computations without blocking UI rendering.
b) A server-side Node.js worker cluster.
c) An automated browser testing bot.
d) A service worker for offline caching.
Correct Answer: a) A script running in a background thread separate from the main execution thread, allowing heavy computations without blocking UI rendering.
Explanation:
Web Workers enable true multi-threaded background processing in web applications.

71. What is a Service Worker?

a) A programmable proxy script running in the background enabling offline caching, push notifications, and network interception.
b) A backend API worker for database queries.
c) An automatic DOM reflow optimizer.
d) A background audio playback worker.
Correct Answer: a) A programmable proxy script running in the background enabling offline caching, push notifications, and network interception.
Explanation:
Service workers act as network proxies between web apps and browser networks, powering Progressive Web Apps (PWAs).

72. What is Shadow DOM?

a) A browser technology providing encapsulation by attaching a hidden, isolated DOM tree to an element, keeping styles separate from the main document.
b) A debugging tool for rendering hidden DOM elements.
c) A memory optimization for unused DOM nodes.
d) A virtual DOM implementation used by React.
Correct Answer: a) A browser technology providing encapsulation by attaching a hidden, isolated DOM tree to an element, keeping styles separate from the main document.
Explanation:
Shadow DOM enables Web Components by encapsulating styles and markup, preventing global CSS leakage.

73. What is function hoisting?

a) The compilation mechanism where function declarations are moved to the top of their scope during creation, allowing invocation before their written line.
b) Converting function declarations into arrow functions.
c) Moving functions into global scope automatically.
d) Optimizing function execution speed in V8.
Correct Answer: a) The compilation mechanism where function declarations are moved to the top of their scope during creation, allowing invocation before their written line.
Explanation:
Function declarations are fully hoisted with their bodies during compilation.

74. What is variable hoisting with `var`?

a) The mechanism where `var` declarations are hoisted to the top of their scope and initialized with `undefined` during compilation.
b) Hoisting variables into global window properties.
c) Assigning default values to let declarations.
d) Deleting unreferenced variables.
Correct Answer: a) The mechanism where `var` declarations are hoisted to the top of their scope and initialized with `undefined` during compilation.
Explanation:
Var declarations hoist and initialize as undefined, allowing access without ReferenceErrors.

75. What is a JavaScript Iterator?

a) An object that implements the `next()` method returning an iterator result object with `value` and `done` properties for sequential traversal.
b) A loop construct like `for...in`.
c) An array map method wrapper.
d) A generator function parameter.
Correct Answer: a) An object that implements the `next()` method returning an iterator result object with `value` and `done` properties for sequential traversal.
Explanation:
Iterators power protocols like `for...of` loops and spread syntax across iterable collections.

76. What is the difference between `for...in` and `for...of` loops?

a) `for...in` iterates over an object's enumerable property keys, whereas `for...of` iterates over iterable values like array items.
b) `for...of` iterates over object keys, while `for...in` iterates over array values.
c) `for...in` only works on maps, while `for...of` works on objects.
d) They perform identical iterations.
Correct Answer: a) `for...in` iterates over an object's enumerable property keys, whereas `for...of` iterates over iterable values like array items.
Explanation:
Use `for...in` for inspecting object keys and `for...of` for traversing iterable values.

77. What is a JavaScript Polyfill?

a) A piece of code that implements modern JavaScript features on older browsers that do not natively support them.
b) A CSS stylesheet normalizer.
c) A compiler plugin for TypeScript.
d) A module bundler plugin.
Correct Answer: a) A piece of code that implements modern JavaScript features on older browsers that do not natively support them.
Explanation:
Polyfills bridge compatibility gaps for older environments lacking modern API implementations.

78. What is Babel in the JavaScript ecosystem?

a) A popular JavaScript compiler that transforms ECMAScript 2015+ code into backward-compatible versions running in older browsers.
b) A module bundler like Webpack.
c) A testing framework for React.
d) A Node.js web server framework.
Correct Answer: a) A popular JavaScript compiler that transforms ECMAScript 2015+ code into backward-compatible versions running in older browsers.
Explanation:
Babel ensures developers can write modern JS while supporting legacy browser environments.

79. What is a module bundler (e.g., Webpack, Vite)?

a) A developer tool that processes application modules, resolves dependencies, and bundles them into optimized static assets for deployment.
b) A minifier for compressing JSON files.
c) A server-side database router.
d) A browser extension for debugging.
Correct Answer: a) A developer tool that processes application modules, resolves dependencies, and bundles them into optimized static assets for deployment.
Explanation:
Bundlers compile multiple JS/CSS modules into optimized bundles ready for browser loading.

80. What is tree shaking?

a) A dead-code elimination technique used during bundling to remove unused export modules and functions from final production bundles.
b) Optimizing DOM tree node hierarchies.
c) Garbage collecting unused memory objects.
d) Minifying CSS stylesheets.
Correct Answer: a) A dead-code elimination technique used during bundling to remove unused export modules and functions from final production bundles.
Explanation:
Tree shaking relies on ES6 static module import/export syntax to drop dead code, reducing bundle sizes.

81. What is the Fetch API?

a) A modern, promise-based JavaScript interface for making HTTP network requests across the web.
b) A database query wrapper for IndexedDB.
c) An asynchronous file reader API.
d) A DOM element selector function.
Correct Answer: a) A modern, promise-based JavaScript interface for making HTTP network requests across the web.
Explanation:
Fetch replaced cumbersome `XMLHttpRequest` objects with clean, promise-driven network requests.

82. What happens when you stringify an object containing a function using `JSON.stringify()`?

a) Functions are completely omitted or converted to null inside arrays, as JSON specification does not support executable functions.
b) It throws a TypeError immediately.
c) It converts function code into string representation.
d) It executes the function during serialization.
Correct Answer: a) Functions are completely omitted or converted to null inside arrays, as JSON specification does not support executable functions.
Explanation:
JSON serialization strips out functions, undefined values, and symbols.

83. What is a race condition in asynchronous JavaScript?

a) A flaw where process output depends on the unpredictable sequence or timing of uncontrollable asynchronous operations.
b) When the CPU overheats during array sorting.
c) When two promises resolve at the exact same millisecond.
d) An infinite recursion stack overflow.
Correct Answer: a) A flaw where process output depends on the unpredictable sequence or timing of uncontrollable asynchronous operations.
Explanation:
Race conditions occur when async operations finish out of expected order, often mitigated using `AbortController`.

84. What is the purpose of `AbortController`?

a) To abort one or more web requests like fetch calls before they complete.
b) To cancel running setTimeout timers.
c) To terminate Web Worker threads instantly.
d) To catch unhandled promise rejections.
Correct Answer: a) To abort one or more web requests like fetch calls before they complete.
Explanation:
AbortController provides a standard signal mechanism to cancel ongoing fetch requests and async tasks.

85. What is dynamic import (`import()`)?

a) A function-like expression that loads modules asynchronously on demand at runtime rather than statically at compile time.
b) Importing modules from external CDN servers dynamically.
c) Reloading browser scripts without page refresh.
d) Parsing JSON strings into modules.
Correct Answer: a) A function-like expression that loads modules asynchronously on demand at runtime rather than statically at compile time.
Explanation:
Dynamic imports (`import('./module.js')`) enable code splitting and lazy loading in modern applications.

86. What is a constructor function in JavaScript?

a) A regular function designed to initialize new objects when invoked with the `new` keyword.
b) A class method that executes automatically upon page load.
c) A function that destroys objects from memory.
d) An IIFE module wrapper.
Correct Answer: a) A regular function designed to initialize new objects when invoked with the `new` keyword.
Explanation:
Before ES6 classes, constructor functions with prototype methods were the primary way to create object blueprints.

87. What happens under the hood when you invoke a function with the `new` keyword?

a) It creates an empty object, links its prototype, binds `this`, executes the constructor, and returns the object.
b) It compiles the function into native machine code.
c) It creates a global window variable.
d) It freezes the constructor function.
Correct Answer: a) It creates an empty object, links its prototype, binds `this`, executes the constructor, and returns the object.
Explanation:
The `new` operator orchestrates object instantiation and prototype chain linkage.

88. What is an iterable in JavaScript?

a) An object that implements the `Symbol.iterator` method, allowing its values to be iterated over using structures like `for...of` loops.
b) Any object with numeric keys.
c) An array with length greater than zero.
d) A frozen object instance.
Correct Answer: a) An object that implements the `Symbol.iterator` method, allowing its values to be iterated over using structures like `for...of` loops.
Explanation:
Built-in iterables include Arrays, Strings, Maps, Sets, and TypedArrays.

89. What is JSON (`JavaScript Object Notation`)?

a) A lightweight, text-based data interchange format derived from JavaScript object syntax used for client-server data transmission.
b) A binary storage format for database records.
c) A compiled bytecode format for V8.
d) An XML schema validation file.
Correct Answer: a) A lightweight, text-based data interchange format derived from JavaScript object syntax used for client-server data transmission.
Explanation:
JSON provides language-agnostic data serialization with clear string formatting rules.

90. What is the difference between `JSON.stringify()` and `JSON.parse()`?

a) `JSON.stringify()` converts an object to a JSON string, whereas `JSON.parse()` converts a JSON string back into an object.
b) `JSON.parse()` converts objects to strings, while `JSON.stringify()` parses HTML.
c) They perform identical serialization operations.
d) `JSON.parse()` only works in Node.js.
Correct Answer: a) `JSON.stringify()` converts an object to a JSON string, whereas `JSON.parse()` converts a JSON string back into an object.
Explanation:
Stringify serializes objects for storage/transfer, while parse deserializes strings back into active objects.

91. What is prototypal delegation?

a) When an object delegates property and method lookups up its prototype chain when a property is not found locally.
b) Delegating event handlers to child nodes.
c) Passing callback functions across Web Workers.
d) Delegating memory allocation to garbage collection.
Correct Answer: a) When an object delegates property and method lookups up its prototype chain when a property is not found locally.
Explanation:
Delegation allows objects to share methods efficiently without duplicating code in memory.

92. What is method overriding in ES6 classes?

a) Providing a specialized implementation of a method in a subclass that already exists in its parent superclass.
b) Deleting a prototype method entirely.
c) Renaming object keys during destructuring.
d) Overwriting global window functions.
Correct Answer: a) Providing a specialized implementation of a method in a subclass that already exists in its parent superclass.
Explanation:
Subclasses can override parent methods to customize behavior while optionally calling `super.method()`.

93. What is the purpose of the `super` keyword in ES6 classes?

a) To call parent constructor methods or access parent prototype methods from within a subclass.
b) To declare global super-admin variables.
c) To make class properties immutable.
d) To export modules to other files.
Correct Answer: a) To call parent constructor methods or access parent prototype methods from within a subclass.
Explanation:
Subclasses must call `super()` in their constructor before accessing `this` to initialize the parent class context.

94. What is a memory heap vs call stack?

a) The Call Stack tracks execution context frames synchronously, whereas the Memory Heap is an unstructured region where dynamic objects are allocated.
b) The Call Stack stores objects, while the Heap stores primitive variables.
c) They are identical memory spaces.
d) The Heap runs on background Web Workers.
Correct Answer: a) The Call Stack tracks execution context frames synchronously, whereas the Memory Heap is an unstructured region where dynamic objects are allocated.
Explanation:
Primitives and execution pointers live on the stack, while dynamic objects and closures reside on the heap.

95. What is a memory leak caused by global variable pollution?

a) Accidentally assigning properties to the global scope without declaration keywords, causing them to persist in memory for process lifetime.
b) Creating too many closures inside arrow functions.
c) Using `Object.freeze()` incorrectly.
d) Spawning excessive worker threads.
Correct Answer: a) Accidentally assigning properties to the global scope without declaration keywords, causing them to persist in memory for process lifetime.
Explanation:
Undeclared assignments attach to the global object, preventing garbage collection and causing memory leaks.

96. Why is mastering advanced JavaScript mechanics crucial for senior software engineers?

a) It forms the foundation of runtime mechanics, asynchronous concurrency, memory management, and robust application architecture.
b) It is only required for writing CSS stylesheets.
c) It eliminates the need for unit testing.
d) It makes V8 compile C++ code.
Correct Answer: a) It forms the foundation of runtime mechanics, asynchronous concurrency, memory management, and robust application architecture.
Explanation:
Deep understanding of core JS mechanics distinguishes senior engineers from junior developers.
← Previous: JavaScript Hoisting MCQs
Next →: JavaScript OOP MCQs for Developer Interviews & Certification
NewJavaScript Prototypes & Inheritance MCQs for Developer Interviews

JavaScript Prototypes & Inheritance MCQs for Developer Interviews

JavaScript implements inheritance exclusively through a prototype-based model rather than traditional class-based mechanics found in languages like Java or C++.…

By MCQs Generator
NewJavaScript OOP MCQs

JavaScript OOP MCQs for Developer Interviews & Certification

Object-Oriented Programming (OOP) in JavaScript allows developers to structure applications into modular, reusable objects that pair state (properties) with behavior…

By MCQs Generator
NewJavaScript Hoisting MCQs

JavaScript Hoisting MCQs

Hoisting is a fundamental mechanism in JavaScript where variable and function declarations are notionally moved to the top of their…

By MCQs Generator