The arguments object is available in all functions. It’s kinda like an array. You can access it with indices (
arguments) and you can get its length (
arguments.length), but that’s it. When you want to turn it into an array, you can call
Array.prototype.slice just like you see here. With the newer ES6 spec, you can just call
However, that’s not why we’re calling
Array.prototype.slice here. In this case, we’re calling
slice in order to make a distinct copy of the arguments object. As far as I can tell, there’s not actually a good reason to do this, though.
Why do we need the arguments object at all? Take a look at how the function is called:
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
The first thing passed in an array. Everything after that is a number. There are three arguments in total. Now take a look at the function signature:
We only have one parameter -
arr. That refers to the array we pass in, but how do we access the numbers that come after the array? Further, how do we do this in a way that lets us pass as many numbers as we want? This is why the arguments object is so useful. You can access anything that’s passed into an array, even if the function isn’t defined to take that thing as a parameter.
console.log(arguments); // [[1, 2, 3, 1, 2, 3], 2, 3]