The function we’re going to be composing for this guide is going to be easy — we want to create a function that takes a number of arguments and adds them all together.
If we perceived how many arguments we’d be taking, this would be a surprisingly simple function to write. We could achieve it by doing something like the following:
Now let’s observe what happens if we pass three arguments into this function:
We are awaiting a sum of 9, but we are still seeing the same output as before: 5. What this tells us is that the function is actually ignoring anything beyond the first two arguments, as that’s all we’ve made space for. Okay, so what if we just build variables for the specific minimum number of arguments we might need? Let’s see what chances:
Now if we pass in too few arguments, the result is NaN. The function cannot take less than the required number of arguments. In order to return the required result, we want to make use of the arguments object. Let’s see what MDN has to say regarding to the arguments object:
Basically, this permits us to access all the arguments given into an appropriate function. Since we can reach the length of this ‘arguments’ object, we can build a simple loop to return the sum of all given arguments.
We can now pass in any numbers we want to add together to get the correct sum returned.
As stated in the MDN reference above, the ‘arguments’ object is not accessible to us when we are using arrow functions. Arrow functions do, however, enable you to take any number of arguments. Instead of an ‘arguments’ object, we can refer to a ‘rest’ parameter. This must be applied in conjunction with the spread operator, but the parameter can be specified any name you’d like to apply. For this function, I’m calling it ‘args.’
As you can notice, very little about the composition of the function has changed. This time we begin with an arrow function, and then we apply the spread operator to pass in the ‘rest’ parameter, which I’ve attributed to the variable name ‘args.’ Then, as with the primary function, we loop over the arguments that were passed in and attach each to the sum. And that’s all you need to do!
Conceivably, this helps you in the prospect when you’re building functions with a variable number of arguments.