JS-Dev-101 practice question 5 of 25

Refer to the code snippet: 01 let array = [1, 2, 3, 4, 4, 5, 4, 4]; 02 for (let i = 0; i < array.length; i++) { 03 if (array[i] === 4) { 04 array.splice(i, 1); 05 i--; 06 } 07 } What is the value of array after the code executes?

Full set: 148 questions
Answer options
A: [1, 2, 3, 4, 5, 4, 4]
B: [1, 2, 3, 4, 4, 5, 4]
C: [1, 2, 3, 4, 5, 4]
D: [1, 2, 3, 5] Correct answer
Correct Answer:
D. [1, 2, 3, 5]
Explanation

The code iterates through the array to remove all elements with the value 4. The splice(i, 1) method removes the element at the current index i, modifying the array in place. When an element is removed, subsequent elements shift to the left. The crucial part is i--, which decrements the index. This ensures that after removing an element, the loop re-evaluates the same index on the next iteration, correctly checking the element that shifted into the current position. This process correctly removes all four instances of the number 4.

Why Incorrect

A. This result would occur if only the first 4 was removed, which is incorrect as the loop continues.
B. This result is not achievable with the given logic; it implies a specific 4 was skipped incorrectly.
C. This result would occur if the i-- was missing, causing the loop to skip the adjacent 4 after the first one was removed.

References

1. MDN Web Docs, Array.prototype.splice(). The documentation explains that splice() changes the contents of an array by removing or replacing existing elements, returning an array containing the deleted elements. It modifies the array in-place.

2. Eloquent JavaScript, 3rd Edition, by Marijn Haverbeke, Chapter 4: Data Structures: Objects and Arrays. The chapter discusses array methods and the consequences of modifying arrays while iterating over them.

Scroll to Top