JS-Dev-101 practice question 6 of 25

Code: 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 execution?

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

The code iterates through the array to remove all elements with the value 4. When array.splice(i, 1) is called, it removes an element, shortening the array and shifting subsequent elements to the left. The next line, i--, is crucial. It decrements the loop counter to ensure that the loop re-evaluates the element that has just shifted into the current index i. This prevents skipping over consecutive duplicate values, resulting in the correct removal of all four instances of 4.

Why Incorrect

A: This would be the result if the loop did not correctly handle consecutive 4s, likely by omitting the i-- statement. C: This would be the result if only the first 4 was removed, which is incorrect as the loop continues to run. D: This would be the result if the loop only removed one of the two consecutive 4s, which the i-- statement correctly prevents.

References

Mozilla Developer Network (MDN). (n.d.). Array.prototype.splice(). "The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place." Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Array/splice

Flanagan, D. (2020). JavaScript: The Definitive Guide (7th ed.). O'Reilly Media. Chapter 7, Section 7.8 discusses array iteration and modification, noting the pitfalls of modifying an array while iterating and the common pattern of decrementing the index to compensate.

Scroll to Top