

An integer that specifies where to end the selection. Use negative numbers to select from the end of an array.Īrgument 2: Optional. An integer that specifies where to start the selection (The first element has an index of 0). The new item(s) to be added to the array.Īrgument 1: Required. And if not passed, all item(s) from provided index will be removed.Īrgument 3.n: Optional. If set to 0(zero), no items will be removed. Splice() method can take n number of arguments:Īrgument 2: Optional. The splice() method changes the original array and slice() method doesn’t change the original array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method returns the removed items in an array. Returns: An array containing the extracted elements. If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array. Last index for extraction but not including (default array.length). If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array. Remove last element (start -> array.length+start = 3)Ĭonsole.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array) If you don't want to change the array, the slice() method can be ('Elements deleted:', array.splice(0, 1), 'mutated array:', array) You can use it if you are fine with modifying the array.

Let us now use all three methods on an array to get the last element and check which method is the fastest let arry = Ĭonsole.timeEnd('array length property') Īs you can see, the pop() method is fastest. This method changes the length of the array. The pop() method pops/removes the last element of an array, and returns it. Providing one index value returns the element at that position & a negative index value calculates the index from the end of the array. The slice() method does not modify the existing array.


This method selects the elements starting at the given start index and ends at the given end index excluding the element at the end index. The slice() method returns specific elements from an array, as a new array object. Therefore the last element's index would be array length-1. The reason we are subtracting 1 from the length is, in JavaScript, the array index numbering starts with 0. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed. The length property returns the number of elements in an array.
