Imagine you have a multiply function, where you don’t know in advance how many arguments you need to pass to it. Here’s where the arguments
javascript object comes pretty handful.
function multiply() { let result = 1; for (let i = 0; i < arguments.length; i++) { result *= arguments[i]; } return result; } console.log(multiply(1, 2, 3));
As you can see we didn’t define any parameters in our multiply function declaration on line 1. However we were able to access the arguments passed to the multiply function (1, 2, 3) through the arguments object. Arguments acts just like an array, but it’s not actually an array object. We can access arguments.length and loop through it, but we don’t have access to the useful functions from Array.prototype
like forEach
, sort
, filter
, map
, reduce
.
Now that we’ve learnt about the arguments object, let’s refactor our code to use the reduce function in order to calculate the product of the arguments passed. Since we can not use reduce on the arguments object, we need to convert the arguments object into an array. Let’s explore 2 ways we can do so.
ES5
We can use Array.prototype.slice(arguments)
to convert the arguments array-like object into an array.
The .call()
and .apply()
methods let you manually set the value of this
in a function. So if we set the value of this
in .slice()
to an array-like object, .slice()
will return an array, and we will be able to use the reduce method.
const multiply = () => { let args = Array.prototype.slice.call(arguments); return args.reduce((acc, curr) => acc * curr, 1); } console.log(multiply3(1, 2, 3, 4));
ES6 rest parameters
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.
const multiply = (...args) => args.reduce((acc, curr) => acc * curr, 1); console.log(multiply(1, 2, 3));
In contrast to the arguments
object that is not a real array, rest parameters are Array
instances, meaning methods like sort
, map
, forEach
or pop
can be applied on it directly.