So, today I want to look at the arguments object, again using MDN as my reference.
First of all, note that this is an object, not a function, so no arguments() stuff. Second, it’s an object, NOT an array. That’s important to remember when using it as well. If you’re not clear on the difference, you should review the concept of an array versus an object.
Now, the arguments OBJECT is available within all FUNCTIONS. You can use it to refer to any function’s arguments. Now, each entry in the object is referred to like so:
You actually use the word arguments to make this work. Let’s say your function is like this:
You would NOT use stuff to refer to the first argument.
You can also, according to MDN, set the value of an argument, like so:
arguments = “this is the value of the 1st argument”;
You can also use the length property on the arguments object:
var howLongIsIt = arguments.length;
Now, the idea here is that we don’t know how many arguments the function is receiving – there could be one, there could be 10. the arguments object lets us access them all. Now, to do stuff with these arguments, we need to convert the arguments OBJECT to a real ARRAY (remember, I mentioned above that they were NOT the same thing!). To do this, MDN suggests:
var args = Array.prototype.slice.call(arguments);
So, let’s say we have a bunch of items that we want to combine into one array. MDN gives the following as an example:
“red”, “orange”, “blue”
Here’s the function to do so:
Let’s unpack that. First of all, we’re using the function myConcat to make all this happen, and passing it a bunch of items as “separator” instead of as the red, orange, etc.
Next, we use the suggestion from MDN to create an array called args.
Then we use the join function to glue all the items in separator into the array called args, and return that array.
What is our output? Well, it’s:
red, orange, blue
And that’s the arguments object in action!