Skip to content
Advertisement

Alternative syntax to access javascript function arguments

(function(arguments = {})
{
    console.log(arguments)
}
)("a","b","c")

prints

$ node args.js 
a
$ node --version
v8.9.4

Is there a way to access the actual arguments in that case?

Advertisement

Answer

I would advise against overriding the built-in arguments variable within a function definition.

You could spread the expected arguments instead using ...vargs.

(function(...vargs) {
  console.log(arguments); // Built-in arguments
  console.log(vargs);     // Variable (spread) arguments
})("a", "b", "c");
.as-console-wrapper { top: 0; max-height: 100% !important; }

Please take a look at the arguments object over at MDN for more info.

The documentation notes that if you are using ES6 syntax, you will have to spread the arguments, because the arguments do not exist inside of an arrow (lambda or anonymous) function.

((...vargs) => {
  try {
    console.log(arguments); // Not accessible
  } catch(e) {
    console.log(e);         // Expected to fail...
  }
  console.log(vargs);       // Variable (spread) arguments
})("a", "b", "c");
.as-console-wrapper { top: 0; max-height: 100% !important; }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement