programming
beginner
10 sample questions
Javascript MCQ Practice Test
Writing scripts for interactivity: alerts, user inputs, and dynamic content.
Understanding event listeners (click, hover) and DOM manipulation.
Q1. What will be the output of the following JavaScript code snippet? `const myArray = [10, 20, 30, 40]; const newArray = myArray.slice(1, -1).map(x => x * 2); console.log(newArray);`
-
A. [20, 60]
-
B. [40, 60] ✓
-
C. [20, 40]
-
D. [10, 20, 30]
Explanation: The `slice(1, -1)` method extracts a portion of the array, starting from index 1 (the second element) and ending before the last element. This results in `[20, 30]`. The `map` method then doubles each element, yielding `[40, 60]`.
Q2. Consider a JavaScript function utilizing async/await and Promises. Within a try...catch block handling a rejected Promise, what will be the value of 'error.message' if the Promise rejection uses `Promise.reject({ message: 'Database Error', code: 500 })`?
-
A. 'Error'
-
B. 'Database Error' ✓
-
C. 500
-
D. undefined
Explanation: The error object caught by the catch block will contain the properties of the object passed to Promise.reject(). Therefore, error.message will directly access the 'message' property of the rejected Promise, which is 'Database Error'.
Q3. Consider a scenario where you're using JavaScript's `Proxy` object to intercept property accesses on a target object. You want to log every attempted property access, regardless of whether the property exists. Which combination of `get` and `has` trap handlers will reliably achieve this, even for properties that don't exist on the target object, without throwing errors?
-
A. Only implementing the `get` trap.
-
B. Implementing both `get` and `has` traps, where `has` returns `true` for all property accesses. ✓
-
C. Implementing only the `has` trap, returning `true` for all accesses.
-
D. Implementing both `get` and `has` traps, where `get` throws an error if the property doesn't exist and `has` returns false.
Explanation: The `get` trap is invoked when a property is accessed. However, if a property doesn't exist and only a `get` trap is implemented, it will typically not be triggered (depending on how the property access is done). The `has` trap is specifically designed to determine if a property exists. By implementing both and having `has` always return `true`, we ensure that `get` is always called, allowing us to log every attempted access, regardless of existence. Option 3 will log the attempts indirectly but doesn't ensure execution of the `get` trap.
Q4. Consider a scenario where you need to deeply clone a complex JavaScript object containing nested functions and circular references, ensuring that modifications to the cloned object do not affect the original. Which approach would MOST reliably achieve this, while also handling potential complexities like prototype inheritance and function closures?
-
A. Using JSON.parse(JSON.stringify(originalObject))
-
B. Implementing a recursive cloning function with type checking and circular reference detection ✓
-
C. Utilizing the spread syntax: { ...originalObject }
-
D. Employing structuredClone() with appropriate handling for function preservation
Explanation: JSON.stringify() cannot handle functions or circular references. The spread syntax creates a shallow clone. structuredClone() is a good option but might need additional handling to properly clone functions depending on the environment. A custom recursive function offers the most control and reliability for handling the complexities of deeply cloning objects with nested functions and circular references, including nuanced scenarios like those involving prototype inheritance and closures, by explicitly managing each data type and preventing infinite loops caused by circular references.
Q5. Consider a scenario where you need to deeply clone a JavaScript object containing nested functions and circular references, ensuring that modifications to the cloned object do not affect the original. Which approach would reliably achieve this, accounting for potential complexities like function preservation and cycle detection?
-
A. Using JSON.stringify() and JSON.parse()
-
B. Employing the spread syntax (...obj)
-
C. Leveraging the Object.assign() method
-
D. Implementing a recursive cloning function with cycle detection ✓
Explanation: JSON.stringify() fails with functions and circular references. The spread syntax and Object.assign() create shallow copies, not deep clones. A recursive function with a mechanism to detect and handle circular references is the only reliable method to achieve a true deep clone in this complex scenario.
Q6. Consider a scenario where you need to deeply clone a complex JavaScript object containing nested objects, arrays, and functions, while ensuring that modifications to the clone do not affect the original. Which approach would be MOST reliable and efficient to achieve this, considering potential circular references within the object?
-
A. Using `JSON.parse(JSON.stringify(originalObject))`
-
B. Implementing a recursive deep clone function that handles circular references using a WeakMap ✓
-
C. Utilizing `Object.assign({}, originalObject)`
-
D. Employing the spread syntax (`...originalObject`)
Explanation: While `JSON.parse(JSON.stringify(...))` might seem convenient, it fails with functions and can be inefficient for large objects. `Object.assign` and the spread syntax only create shallow copies. A recursive function with a WeakMap to track visited objects is the most robust solution for handling deeply nested objects and circular references, ensuring a true deep clone without infinite recursion.
Q7. Consider a scenario where you need to deeply clone a JavaScript object containing nested objects and functions, preserving the functionality of those functions. Which approach would reliably achieve this, accounting for potential circular references and ensuring the cloned object is completely independent of the original?
-
A. Using `JSON.parse(JSON.stringify(originalObject))`
-
B. Implementing a recursive cloning function with type checking
-
C. Utilizing `Object.assign({}, originalObject)`
-
D. Employing a structured cloning algorithm that handles circular references ✓
Explanation: While `JSON.parse(JSON.stringify(...))` seems tempting, it fails with functions and circular references. Recursive cloning is possible but prone to errors with complex structures and circular references. `Object.assign` only creates a shallow copy. A structured cloning algorithm, often found in libraries or implemented manually, is the most robust solution for handling complex objects, including functions and circular references, ensuring a truly independent deep clone.
Q8. Consider a scenario where you need to optimize a JavaScript function that processes a large array of objects. The function involves multiple nested loops iterating through this array. Which of the following approaches would MOST significantly improve performance in this specific case, assuming the objects are complex and the array size can reach millions of elements?
-
A. Implementing a more efficient sorting algorithm before processing the array.
-
B. Using Web Workers to parallelize the processing across multiple threads. ✓
-
C. Refactoring the nested loops to use a single, optimized iterative approach.
-
D. Employing memoization to cache intermediate results within the nested loops.
Explanation: While all options might offer some performance improvements, using Web Workers provides the most substantial boost for very large arrays. Web Workers allow for parallel processing, effectively distributing the workload across multiple threads, significantly reducing overall execution time. Sorting or optimizing loops are less impactful when dealing with a massive dataset. Memoization, while useful in other contexts, wouldn't be as beneficial here as the computations involved across the many objects are likely independent.
Q9. Consider a scenario where you're using a JavaScript library that relies heavily on prototype inheritance. You encounter a performance bottleneck related to method lookups on deeply nested prototype chains. Which technique would MOST efficiently address this bottleneck, minimizing the impact on existing code and avoiding significant refactoring?
-
A. Replacing prototype inheritance with composition using mixins. ✓
-
B. Implementing a custom optimized method lookup mechanism within the library.
-
C. Utilizing a JavaScript engine with enhanced prototype chain optimization features (e.g., changing engines).
-
D. Refactoring the library's entire architecture to use a different inheritance model.
Explanation: While changing engines or refactoring is possible, it's resource-intensive and disruptive. A custom lookup mechanism is also a significant undertaking. Using mixins offers a targeted solution, improving performance by reducing the depth of prototype chains without wholesale code changes. Mixins provide a more direct and efficient method access compared to traversing nested prototypes.
Q10. Considering a scenario where you need to deeply clone a JavaScript object containing nested functions and circular references, which approach would reliably avoid issues like stack overflow errors or preserving function references to the original object, while also maintaining the circular references?
-
A. Using JSON.stringify() and JSON.parse()
-
B. Employing the spread syntax (...obj)
-
C. Leveraging the Object.assign() method
-
D. Implementing a recursive cloning function with a WeakMap to track visited objects ✓
Explanation: JSON methods fail with functions and circular references. Spread syntax and Object.assign() create shallow copies, which are insufficient for deeply nested objects, particularly those with circular references. A recursive function using a WeakMap to detect and handle circular references provides the most robust and reliable deep clone in this complex scenario.
That was just a sample. Sign up to unlock the full question bank with timed tests and certificates.
Sign Up Free