Question 13
Back to Exercise
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
const nums = [2, 4, 5, 6, 8];
for (let i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) nums.splice(i, 1);
}
console.log(nums);
- A splice does not work inside loops
- B After splice, the next element moves into index i but the loop moves on to i + 1, so it is skipped – loop backwards or use filter Correct
- C % 2 does not detect even numbers
- D nums must be declared with let
Correct Answer: Option B
Removing 2 shifts 4 into index 0, which is never checked; the same happens to 8 after 6 is removed. nums.filter(n => n % 2 !== 0) gives [ 5 ].
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!