For more tips like this, sign up to the weekly newsletter!

How to get all the function arguments

Let's say there is a function and you want to add some logging. And for that, you need all the arguments that were passed.

The simples solution is to copy-paste the argument names from the function definition:

const f = (a, b) => {
  console.log([a, b]); // [1, 2]
  ...
}

f(1, 2);

But when there is a new parameter, the collection has to be updated too.

Use rest parameters

One solution is to use rest parameters and destructure it in the function body:

const f = (...args) => {
  console.log(args); // [1, 2]
  const [a, b] = args;
  ...
}

f(1, 2);

This is a cumbersome way to collect the arguments. Not only it needs an extra line to name the values, but also you lose information from the function signature, making IDEs less able to assist you.

Combine rest and spread parameters

To combine the previous two solutions, you can use rest parameters to collect all arguments, and pass them to an inner function:

const f = (...args) => {
  console.log(args); // [1, 2]
  ((a, b) => {
    ...
  })(...args);
}

f(1, 2);

Unfortunately, this also combines the drawbacks of the two previous solutions.

Use traditional functions

Traditional functions have a magic arguments variable just for this. So the best solution is to use that instead of an arrow function:

f = function(a, b) {
  console.log(Array.from(arguments)); [1, 2]
  ...
}

f(1, 2);
Try it
References
Learn more: