Let us start with the function given below:
So, you can rewrite above add function to achieve same output using the arguments object as shown in the listing below:
Key features of arguments object are as follows:
- It is an array like object but not an array.
- Number of parameters passed to function can be find using the argument.length inside the function.
- Other arrays methods like push, pop etc. are not allowed on arguments object.
- If there are three parameters passed to function then using argument object they can be accessed as :
Consider the below function foo,
In above function, number of parameters passed to function foo is find-using arguments.length and all passed parameters are accessed in the loop using arguments[i]. For above code output would be as shown in the image below:
Code listed above will throw you exception as shown in the image below:
Keep in mind that using the square bracket you can change value of a specific item in arguments object. Let us consider the code listed below:
In above code snippet,
num2 = arguments
So, if we change value of arguments, value of num1 will be also changed. Also you seen that in the function value of passed parameter can be changed using the square bracket. Therefor output of above code snippet would be 10 instead of 5 as shown in the image below:
Now, you can say that arguments object is not an array; rather it is array like object. It does not have any array properties except of length property.
Besides length property arguments object has other properties argument.callee : It returns the currently executing function.
Output of above code would be function foo as shown in the below image:
Converting arguments object to array
You may come across requirement to convert arguments object to array. You can do that using the Array.from function.
Output of above code snippet would be 78, which last parameter is passed to the function. Other example, we could take to write a function, which will concatenate all the strings passed to it,
Above code snippet will give you output as shown in the image below:
In real scenarios, you may have to convert arguments object to array to use it in ways that are more effective. Last but not least keep in mind that arguments are an object. Therefore, when you print type of arguments, you will get output object.