var args = Array.prototype.slice.call(arguments, 1);
I noted then that the slice() function “takes part of an array and copies it into another array”. Let’s dig a little deeper. Per MDN, the syntax for the slice() function is:
Okay, so obviously arr is the array that we are copying. There are two parameters, begin and end, and both are optional (that’s why they’re in brackets).
will give you
3, 7, 8
Now, you can do begin with negative numbers too, and this tells it to start at the END and work backwards.
The default (if you don’t give it a value) is 0, and begin will “begin” at the beginning, aka element of your array.
Next is the end parameter. This tells slice() where to STOP. Note that slice() stops at the element BEFORE end. That means that end is NOT included! The example given by MDN is
and this will give you elements 1, 2, and 3 from your array. Note that this does not return element arr, because begin is set to 1, and it does not give you element arr, because end is NOT included.
As with begin, negative numbers can be used for end. MDN notes that if you give the command:
you will get the third through the second to last element in your array. So let’s say your array is arr = [2, 4, 6, 8, 10, 12]. the above command will return 6, 8, 10. Remember that the third element in your array is arr, not arr, and that’s why the items return start with 6 and not 4. Second to last is 10.
As with begin, there is a default, and if you don’t give a value for end, the extraction will continue to the last element in the array.
Now, it should be noted that slice() does NOT modify your original array. In the examples above, arr stays the same as it was before the slice operation. Chances are you will store your results in a new variable, like so:
var newArray = arr.slice(0, 3);
newArray gets the copied items, arr stays exactly the same. Likewise, if you add something to newArray, arr won’t change, and vice versa. Another thing to note is that if your array items are strings (“red”, blue”, “green”), you won’t get back something like “r”, “e”, “d”, etc.