Why doesn't array.splice() work when the array has only 1 element? Why doesn't array.splice() work when the array has only 1 element? arrays arrays

Why doesn't array.splice() work when the array has only 1 element?


Because it returns what was removed, which is [1] in your case. arr will be empty after the call.

See example:

let arr = [1];arr.splice(0, 1);console.log(arr);


Array.prototype.splice() returns an array of the deleted elements.

Your are logging the returned value of the operation not the current state of the array.


The splice() method changes the contents of an array by removing existing elements and/or adding new elements. Reference

The syntax of this method is:

array.splice(start)array.splice(start, deleteCount)array.splice(start, deleteCount, item1, item2, ...)

You are using the second syntax and passing 0 as start and 1 as deleteCount that means you would like to start at 0th index and delete 1 item (not 1 as value in array).

This method returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

So, in this case the result is [1] i.e. an array with value of 1 that is the item you just deleted.