Consider the following code:
What if we wanted to add four numbers? We would either need to declare a whole new function, assign some extra variables, or use our “addTwoNumbers” function in a pretty awkward way:
But what if we wanted to add five numbers? Do we really want to write a new function for every different quantity of numbers, or find some clever way to use our simple adding function?
Some of you might be thinking, “how about the reduce method on arrays!?”
Using “reduce” with the “addTwoNumbers” function is a step in the right direction. But we would first need to push all our numbers to an array:
The “arguments object” is an array-like object that stores all the parameters passed to a function…even if the function declaration doesn’t specify any parameters.
However, the “arguments object” is not like other arrays:
- We can access values normally with bracket notation
- The length property is available
- And that is it. No other array methods can be used on it
So….in comes “Array.prototype.slice.call(arguments)”.
There is a lot going on in the above statement. Essentially what we are doing is using the slice method that all arrays have and then coercing it to work with an object using “call”. “Call” — and “apply” — allow us to redirect the “this” property from one object to another.
Let’s write a new “add” function now that we know how to handle an indeterminate number of inputs:
You might be saying, “that’s some sweet code and all, but how am I going to to remember a mouthful like ‘Array.prototype.slice.call(arguments)’?”
Whenever you need to make an “argsArray” (or arrrrrrrrgsArray), just imagine a pirate on the shores of North Carolina. The infamous Blackbeard and his clan of raiders would often lure (or “call”) ships to treacherously shallow waters with fake lighthouses. Then they would jump out with their weapons and grab (or “slice”) all the booty (or “arguments”).
If you find some of the syntax in “addAllTheNumbers” a bit confusing stay tuned for my next post. ECMAScript 2015 and syntactic sugar.