170k views
2 votes
What happens if we give Array.splice() an index that is negative?

User Annndrey
by
7.6k points

1 Answer

6 votes

Final answer:

If we give Array.splice() a negative index, it counts from the end of the array. For example, if we have an array with 5 elements and we provide an index of -2, it will remove the second-to-last element.

Step-by-step explanation:

If we give Array.splice() a negative index, it counts from the end of the array. For example, if we have an array with 5 elements and we provide an index of -2, it will remove the second-to-last element. The negative index starts counting from -1, so the last element has an index of -1, the second-to-last has an index of -2, and so on.

Here's an example:

let array = [1, 2, 3, 4, 5];
array.splice(-2, 1);
console.log(array);
// Output: [1, 2, 3, 5]

In this example, the element with index -2 (which is 4) is removed from the array.

User Jeff Walters
by
8.8k points