I know that when it comes to array.slice() what we normally do is this:

var arr = [1,2,3,4];
var zeroOne  = arr.slice(0,1);

and the 0 means it starts to cut from arr[0] ; 1 means it stops cutting before arr[1], so in this case var zeroOne===1, because we specifically said: “we want you to cut the array from element 0, and only cuts one element”

then why does var one = arr.slice(1) gives you 2,3,4???

is it because what arr.slice(1) actually means arr.slice(1, to the end) ??

Yes: in this case, this is an example of why it’s important to read the documentation


Whenever you do not provide the second argument to slice(), all the elements to the end of the array will be selected.

arr.slice(1) // returns [2,3,4]


arr.slice(2) // returns [3,4]

One more feature of slice is that you can use negative indexes to select elements from end of the array.
For example:

arr.slice(-1) // returns [4]
arr.slice(-2) // returns [3,4]
1 Like

@aditya_p @DanCouper thanks for the confirmation!

… also this:

// Give me semi-last
[1,2,3].slice(-2, -1) // 2

// Make a copy of my array in pre-ES6 fashion
[1,2,3].slice() // new [1,2,3]
1 Like

:tired_face: my head is gonna blow up.