Official information on `arguments` in ES6 Arrow functions?

12.1k views Asked by At
(() => console.log(arguments))(1,2,3);

// Chrome, FF, Node give "1,2,3"
// Babel gives "arguments is not defined" from parent scope

According to Babel (and from what I can tell initial TC39 recommendations), that is "invalid" as arrow functions should be using their parent scope for arguments. The only info I've been able to find that contradicts this is a single comment saying this was rejected by TC39, but I can't find anything to back this up.

Just looking for official docs here.

2

There are 2 answers

1
Bergi On BEST ANSWER

Chrome, FF, and node seem to be wrong here, Babel is correct:

Arrow functions do not have an own arguments binding in their scope; no arguments object is created when calling them.

looking for official docs here

Arrow function expressions evaluate to functions that have their [[ThisMode]] set to lexical, and when such are called the declaration instantiation does not create an arguments object. There is even a specifc note (18 a) stating that "Arrow functions never have an arguments objects.".

6
Mulan On

As noted by Bergi, arrow functions do not have their own arguments variable.

However, if you do want to capture the args for your arrow function, you can simply use a rest parameter

const myFunc = (...args) =>
  console.log ("arguments", args)
  
myFunc (1, 2, 3)
// arguments [1, 2, 3]

Rest parameters can be combined with other positional parameters, but must always be included as the last parameter

const myFunc = (a, b, c, ...rest) =>
  console.log (a, b, c, rest)

myFunc (1, 2, 3, 4, 5, 6, 7)
// 1 2 3 [ 4, 5, 6, 7 ]

If you make the mistake of writing a rest parameter in any other position, you will get an Error

const myFunc = (...rest, a, b, c) =>
  console.log (a, b, c, rest)
  
myFunc (1, 2, 3, 4, 5, 6, 7)
// Error: Rest parameter must be last formal parameter