Recently, been working on some algorithms. One question, I recently worked on involved taking in any number of positive integers and returning a value. Now this was a bit weird for me, normally when. constructing a function you declare your arguments or parameters for the function before hand but how to work with an unknown number… enter arguments.
lets say for example I need to find the sum of integers passed into a function, if I had 2 numbers I could write something like this in JS
But what if I had to take all numbers, like num1, num2 … num10. My functions would pick up the first 2 and ignore the rest. Unbeknownst to me there exists an object in functions called arguments, which if logged with 10 integers shows this.
As you can see, I’m picking up the first 2 and return 3 at the end of the function, but arguments is giving me key value pairs with the inputs in. Although it is an object, arguments behaves like an array which is why the keys are similar to the index of an array. So
arguments = 2 which seems straightforward. Arguments also has a length property which is not found in objects such as arguments.length would equal 10. Otherwise there is are no other array methods available for arguments. However, we have plenty of object methods we can evoke using arguments.
Note: You can turn arguments into an array using a few methods as an example.
let args = Array.from(arguments);
let args = [...arguments];
Using this specific input and function, I can retool my sumOfNums to add all my parameters being used when I call the function. I can iterate through the object using a for… in iterator. While I could keep num1 and num2 variables, it would just be confusing when you look at it and iterate, so ill be omitting them.
Since the parameters exist in arguments as my keys, using the arguments[key] will give me the inputs, which I can add to my sum variable and return the sum of the inputs being feed into my function.
I will say there is a lot of interesting functionality with arguments, such as you can use the spread operator to initialize arguments as an array
I feel like I will go on forever, but I’ll attach the MDN documentation for your reference. I’d definitely take look, since it’s an added functionality I just found out about =) Maybe it will be your first introduction as well.
Well till next time