user619271
user619271

Reputation: 5022

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?

Upvotes: 2

Views: 163

Answers (2)

bel3atar
bel3atar

Reputation: 943

function f1() { console.log(Array.from(arguments)) }
f1(1, 2, 3)

function f2(...args) { console.log(args) }
f2(4, 5, 6)

Upvotes: 4

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

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; }

Upvotes: 4

Related Questions