Middle
Have you handled a situation where indexOf returns -1 when used in removeItem?
sobes.tech AI
Answer from AI
Yes, I have encountered a situation where indexOf returns -1 when trying to remove an element from an array.
If you use indexOf to find the index of an element and then call splice without checking, you might accidentally remove the last element of the array, since array.splice(-1, 1) will remove the last element.
The correct approach is to always check the result of indexOf before removing:
function removeItem(array, item) {
const index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
// If index === -1, the element is not found, do nothing
}
This prevents unwanted modifications to the array and logical errors.